12

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?

3
  • 4
    If it interacts with web services and databases, then it is not a unit test. A unit test tests code in isolation. Apr 25, 2014 at 8:34
  • use an in-memory database for these sort of integration tests Apr 25, 2014 at 8:34
  • you should replace your Database with a dummy and assert against it, as John wrote a UnitTest should not interact with a database at all.
    – quadroid
    Apr 25, 2014 at 8:35

4 Answers 4

16

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.

1

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.

1

Mocking is a good way to do it.

It you want more integration test-like approach (which can be helpful when you want to test actual database interaction), you can use a local running MySql server instance.

I've created a project that let you run tests on a live MySql server without setting it up.

You can download it a Nuget package (Mysql.Server) or check it out here: https://github.com/stumpdk/MySql.Server

1

You can also look for Microsoft fakes framework. https://learn.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.