Fiona
Fiona

Reputation: 1599

unit testing and mocking the db

I have an assembly that has one public method. I'd like to write a unit test for this method. To create an instance of this class, the default constructor is called. I cannot change this. All this method does, is examine the object passed into the method and depending on the value updates a table in the database. For the unit test I want to verify that the db call was made. I would like to mock the database. What is the best way of doing this. So far, I've added a property which is of type IRepository. In the method, if this is null I create an instance of the Repository. My thoughts are that in the unit test I will set this property to a Mocked Repository. Does this sound ok?

public IRepository DatabaseInstance { get; set; }

public void Process(ObjectContext context)
{
    if (DatabaseInstance == null)
        DatabaseInstance = new UpdateRepository();
    // Depending on value in context, set up values of sprocToCall and listOfParameters

    //Eventually call UpdateTable
    DatabaseInstance.UpdateTable(sprocToCall, listOfParameters);
}

Upvotes: 1

Views: 3181

Answers (1)

mark_h
mark_h

Reputation: 5467

It looks like you are pretty much there already. You just need your mock class like this;

public interface IRepository
{
    void UpdateTable(string sprocToCall, List<string> listOfParameters);
}

public class MockRepository:IRepository
{
    public string SprocToCall { get; set; }
    public List<string> ListOfParameters { get; set; }
    public void UpdateTable(string sprocToCall, List<string> listOfParameters)
    {
        SprocToCall = sprocToCall;
        ListOfParameters = listOfParameters;
    }
}

I've included the interface I used because it may not be identical to your version of IRepository.

Instead of passing in your real implementation you can set your IRepository property to a version of the mock class above. You would then be able to look at the mock class to determine whether your class was calling UpdateTable correctly. It sounds like that is what you were planning to do anyway so to answer your question; yes - it sounds Ok.

An alternative to using your own mock class (they start to build after a while) would be to use a mocking framework such as NSubstitute or Moq, it's more of a learning curve but quicker in the long run.

Upvotes: 1

Related Questions