Novastorm
Novastorm

Reputation: 1458

Moq framework: simulating adding an object

I have just started out using Moq for unit testing have have run into an issue when trying to add an object to our repo. Basically, we have an interface which represents the structure of our DB. This interface contains additional interfaces that represent the data within that DB, like this:

public interface IUnitOfWork : IDisposable
{
    IRepository<Order> OrdersRepo { get; }
    IRepository<Customer> CustomerRepo { get; }
    IRepository<Product> ProductsRepo { get; }
}

Creating the mock IUnitOfWork is no problem, the issue arises when I attempt to add an order object to the OrdersRepo, like this:

[TestClass]
public class OrderTest
{
    private Mock<IUnitOfWork> mockDB = new Mock<IUnitOfWork>();
    private IUnitOfWork testDB;
    private Order testOrder;

    [TestInitialize]
    public void Initialize()
    {
        //Create the test order
        testOrder = new Order();
        testOrder.ID = 123;

        //Setting up the Moq DB
        testDB = mockDB.Object;
    }

    [TestMethod]
    public void AddOrder_ValidOrder_OrderAdded()
    {   
        testDB.OrdersRepo.Add(testOrder);
    }
}

I keep getting a NullReferenceException when I attempt to add the order. I think this is because the OrdersRepo inside the testDB is an interface. However when I tried to create a mock repo for this I get an error saying that the OrdersRepo is readonly because it is { get; } and not { get; set; }.

Is it possible for me to use Moq to test adding my order object when the repo is only get; and is an interface?

Upvotes: 0

Views: 372

Answers (2)

Carlos Torrecillas
Carlos Torrecillas

Reputation: 5756

If you want to test your orders repo then you shouldn't need to go through the IUnitOfWork and then mocking the Orders repo basically because that way you are not testing your subject. You should be instantiating your concrete of Orders repo and invoke the Add method that should be publicly accessible. Perhaps you will need to mock your underlying DB client your orders repo is invoking to call the DB, but that's another story.

Hope that helps.

Upvotes: 0

Dovydas Šopa
Dovydas Šopa

Reputation: 2300

You're getting NullReferenceException because you haven't setup mock object. If you want to setup only 1 property, use

mockDB.SetupProperty(self => self.OrdersRepo);

If you want to setup property to use your own enumerable, you can use

var collection = <Init collection here>;
mockDB.SetupGet(self => self.OrdersRepo).Returns(collection);

Or if you want to setup all properties you can use

mockDB.SetupAllProperties();

Upvotes: 3

Related Questions