Modifying Unit Test Database Functions?

I have methods like this:

public static bool ChangeCaseEstimatedHours(int caseID, decimal? time)
   {
       Case c = Cases.Get(caseID);

       if (c != null)
       {
           c.EstimatedHours = time;
           return Cases.Update(c);
       }

       return false;
   }

   public static bool RemoveCase(int caseID)
   {
       return Cases.Remove(caseID);
   }

      

which internally uses LINQ to execute queries.

I am wondering how I should be testing them. They have no state, so they are static. They also modify the database.

Thus, I would have to create a case and then remove it in the same test, but the unit test should only do one thing. What is usually done in these situations?

How can I check queries, updates and deletions of databases?

thank

+3


source to share


3 answers


There is a difference between "Knowing the path and walking the path." What you want to test would be a class as an integration test, not a unit test. A unit test is something that runs in isolation without any external dependencies and therefore makes the test workable even if the machine you are running it on does not have a physical database instance present on it. See More differences here .

This is why patterns such as the repository are really popular when it comes to persistence-based applications, as they help unit test the data layer through Mocking. See a sample here .

So you have 2 options (blue pill or red pill):



Blue Pill: Buy a tool like the TypeMock Isolator is important or JustMock and you can mock anything in your code and the story ends.

Red Pill: Reorganize your existing data layer design into one of the UI-based templates and use free Mocking frameworks like Moq or RhinoMocks and "see how deep the rabbit hole goes"

All the best.

+1


source


The test that requires database access is probably the hardest test to maintain. If you can not touch the database in the unit test, I would try to create an interface for the Cases class.

interface ICase
    {
        ICase Get(int caseID);
        bool RemoveCase(int caseID);
    }

      



And then use RhinoMock, Moq to check if Get () and RemoveCase () were called.

If you insist on the need for database testing, you will need to spend time setting up the testing database and cleaning up the data.

+2


source


Perhaps you could consider a Rails perspective based approach:

  • Initialize content of database tables using presets (fixtures in Rails)
  • Open transaction
  • Launch test
  • Rollback a transaction
  • Go to step 2.with another test
+1


source







All Articles