Dependencies in Unit Tests

87 Views Asked by At

From what I've read on the subject, each unit test should be independent and not rely on the results or success/failure of any other test. Makes good sense to me.

How best to write tests that have dependencies then? Take the simple example like a file system that has a Create() and a Delete() method that you wish to test. The Delete() method needs to the file to exist for it to delete, so how does it satisfy this condition? Calling Create() would introduce a dependency. Similarly, what if the Create() method is supposed to fail if the file already exists? A valid test then would need to call Delete() first to make sure the file didn't exist already.

Is there a way to do a conditional SetUp and TearDown depending on which test is running to solve this? Or should the test itself be a CreateAndDelete test that does both?

1

There are 1 best solutions below

0
On BEST ANSWER

Not depending on another test doesn't mean you can't utilize other methods in the class that you are testing. So for testDelete() you could create a file and then delete it. For testCreateFailOnDuplicate() you could create a file and then try to create it again, validating that it threw an error.

What you don't want to do is the write a testCreate() test and then a testDelete() test that assumes that the testCreate() test already ran -- this is bad form, plus not all test harnesses guarantee a predictive order of tests.

Hope this helps.