Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test a class that's meant to talk to data?

I have a few repository classes that are meant to talk to different kinds of data, deriving from an IRepository interface.

In implementations, the code talks to a data source, be this a directory of XML files or a database or even just a cache. Is it possible to reliably unit test any of these implementations? I don't see a mock implementation working, because then I'm only testing the mock code and not the actual code.

like image 647
Arda Xi Avatar asked May 02 '10 11:05

Arda Xi


People also ask

Should unit tests connect to database?

Unit tests shouldn't depend on infrastructure There's no way to test this function without having a database connection available at the time of testing. If a new developer clones the project they will need to set up a database or else tests will fail.

What should a unit test class check?

The most important thing about a unit test is to explain and show the behavior and logic of the tested component. Some of the developers have the practice to use tests instead of documentation. Good unit tests should be reproducible and independent from external factors such as the environment or running order.


1 Answers

No, you'd use a mock when you were writing a class which uses an IRepository. For the implementations of IRepository, you'd need to test against the appropriate data source. For databases, that's a bit of a pain - for a file system, slightly less so.

Where possible, if you can express your implementation in terms of streams or readers, you will make your life easier: tests for those parts of the implementation can go against in-memory data sources, or streams from resources in the test assembly. Of course you'll probably need some tests which go to a real database or the file system, but hopefully fewer.

Whether you'd call such tests "unit" tests or not is a matter of how you define unit tests; personally I don't care too much about the names involved, but I do care about having tests. For databases in particular, these can be somewhat painful (especially if you want to be able to run tests in parallel) - but they can also be incredibly valuable, in my experience.

like image 156
Jon Skeet Avatar answered Sep 21 '22 02:09

Jon Skeet