Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to enforce that unit tests should never talk to a live database/webservice?

My team continues to find more and more value in the unit tests we write. We don't generally unit test the data access layers of our applications, as they don't contain "logic". In my experience we've run into significant performance issues and non-reproducible errors as a result of letting developers write unit tests that talk to live databases (or webservices) and as a result more and more developers are creating mocks that feed data to these unit tests.

Taking this approach has increased the speed of the tests and isolated testing to the logic rather than testing the connection/retrieval at the same time. I'm wondering if this sounds reasonable to enforce as a coding standard. What are the pros/cons regarding unit testing live databases/webservices that I'm missing?

like image 793
The Matt Avatar asked Mar 04 '10 18:03

The Matt


People also ask

Should unit tests interact with database?

Unit tests should never connect to a database. By definition, they should test a single unit of code each (a method) in total isolation from the rest of your system. If they don't, then they are not a unit test.

Can database be mocked for unit testing?

Yes, absolutely! Because our code that talks to the real DB is already tested carefully in the previous lecture. So all we need to do is: make sure that the mock DB implements the same interface as the real DB. Then everything will be working just fine when being put together.


1 Answers

The database and webservice parts of your application should be tested as well, but by definition they will not be unit tests, but integration tests. These tests would be separate from your unit tests and run less often, but will provide very valuable early detection of defects.

like image 63
Matthew Vines Avatar answered Nov 15 '22 16:11

Matthew Vines