Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using unit tests and a test database

How would I use NUnit and a test database to verify my code? I would in theory use mocks (moq) but my code is more in maintenance shape and fix it mode and I don't have the to setup all the mocks.

Do I just create a test project, then write tests that actually connect to my test database and execute the code as I wwould in the app? Then I check the code with asserts and make sure what I'm requesting is what I'm getting back correctly?

like image 730
cdub Avatar asked Dec 07 '12 22:12

cdub


2 Answers

How would I use NUnit and a test database to verify my code? I would in theory use mocks (moq) but my code is more in maintenance shape and fix it mode and I don't have the to setup all the mocks.

Using mocks is only useful if you want to test the exact implementation behavior of a class. That means you are literally asserting that one class calls a specific method on another class. For example: I want to assert that Ninja.Attack() calls Sword.Unsheath().

Do I just create a test project, then write tests that actually connect to my test database and execute the code as I wwould in the app? Then I check the code with asserts and make sure what I'm requesting is what I'm getting back correctly?

This is just a plain old unit test. If there are no obstacles to achieving this, that's a good indicator that this is going to be your most effective method of testing. It's practical and highly effective.

There's one other testing tool you didn't mention, which is called a stub. I highly recommend you read this classic article for more info:

http://martinfowler.com/articles/mocksArentStubs.html

like image 96
Dan Ling Avatar answered Oct 23 '22 22:10

Dan Ling


Since we are not talking about theoretical case, this is what I would do - From my understanding what you want to test is that whether your app is properly connecting to the DB and fetching the desired data or not.

  1. Create a test DB with the same schema
  2. Add some dummy data in that
  3. Open a connection to the DB from the code, request desired data
  4. Write assertions to test what you got from the DB against what you expected

Also, I don't think these tests should be called unit tests because they are not self contained and are dependent on other factors like whether your database is up and running or not. I would say they fall close to integration tests that will test if different components of your applications are working as expectation when used together.

(Dan's answer ^^ pretty much sums what I wanted to say)

like image 30
TheZelus Avatar answered Oct 24 '22 00:10

TheZelus