How to apply TDD to read/write functions

iotdd

It seems like a chicken and egg problem.

You can make a write function write to some data store, but never know you saved it properly without a tested read function.

You can make a read function read from a data store, but how do you put stuff in that data store, to read, without a tested write function?

EDIT:

I am connecting to and making transactions with an SQL database to save and load objects for use. There's no point testing the access functions the DB provides, but I wrap such DB functions to serialize/deserialize the objects. I want to be sure I'm writing and reading the right stuff to and from the DB correctly.

It isn't like add/delete, as @snowman mentions. I want to know that the contents I've written are correct, but that requires a well-tested read function. When I read, I want to be sure that my read has correctly created an object equal to what was written; but that requires a well-tested write function.

Best Answer

Start with the Read Function.

  • In the test setup: create the database and add test data. either via migration scripts or from a backup. As this is not your code, it doesn't require a test in TDD

  • In the test: instanciate your repository, point at at your test db and call the Read method. Check that the test data is returned.

Now you have a fully tested read function, you can move to the Write function, which can use the existing Read to verify its own results