Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test code that interacts with database without creating data in database

I want to test my C# code in Visual Studio with unit tests. The code interacts with a MySQL database.

An example of what I want to test
A user opens my application and will be saved in the database via a webservice. Now I want to know if the table Users has one more row before the new user came. But if I test the method in the webservice, which will create a record in the database, test data will be in the database. And I don't want test data in my database.

Is there a solution for this problem?

like image 584
Jeffrey Avatar asked Apr 25 '14 08:04

Jeffrey


People also ask

Can unit tests use databases?

To test an application it is not enough to use unit tests. You must also perform functional testing and regression testing. Database access falls outside the scope of unit testing, so you would not write unit tests that include database access.

Should unit tests touch the database?

Unit tests are supposed to test isolated pieces, and sure unit tests should not touch the database. And we can agree with that. But it happened that “unit test” term is far more popular then “integration test”. Unit test have one very strong requirement.

Should you mock database in unit tests?

Mocking and stubbing are the cornerstones of having quick and simple unit tests. Mocks are useful if you have a dependency on an external system, file reading takes too long, the database connection is unreliable, or if you don't want to send an email after every test.


2 Answers

I think what you're looking for is mocking. This allows you to simulate your data access code in order to test your business logic.

There are lots of good frameworks out there including moq and rhino mocks.

If you want to actually populate your database in order to test your data access layer then you're looking for more of an integration test. I've written quite a thorough answer covering my approach to db integration tests here.

like image 175
Liath Avatar answered Nov 08 '22 19:11

Liath


What you are looking for is a Mock. For example Moq for C#.

Wrap your database logic in an interface and mock it in your unit test. That way you can interact with the mocked database logic, without really executing it.

like image 23
Edwin van Vliet Avatar answered Nov 08 '22 19:11

Edwin van Vliet