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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With