简体   繁体   中英

Mock Generic Repository with Moq

I'm using Moq and trying to mock a IDummyRepository which implements IGenericRepository interface, and need to verify a call for the Add method of IGenericRepository. But with the example code below I'm getting a MockException.

If I replace the IGenericRepository in the ServiceDummy for the IDummyRepository the test works, but not in the way I need.

How this can work?

[TestClass]
public class DummyServiceSpec
{
    protected DummyService service;
    protected DummyModel model;

    [TestClass]
    public class Work : DummyServiceSpec
    {
        [TestMethod]
        public void ExpectToWork()
        {
            var repositoryMock = new Mock<IDummyRepository>();
            var serviceDummy = new ServiceDummy(repositoryMock.Object);
            var entity = new Dummy { DummyString = "DummyString" };

            serviceDummy.Add(entity);

            repositoryMock.Verify(r => r.Add(It.IsAny<Dummy>()), Times.AtLeastOnce());
        }
    }
}

public class ServiceDummy
{
    protected IGenericRepository<Guid, Dummy> dummyRepository;

    public ServiceDummy(IDummyRepository dummyRepository)
    {
        this.dummyRepository = dummyRepository;
    }

    public virtual void Add(Dummy entity)
    {
        this.dummyRepository.Add(entity);
    }
}

Try moving your code of repository expectations to your Moq setup of the repository. Since the Add() method is a void, there is no result to check but you can make it verifiable to test that it is actually called.

[TestMethod]
public void ExpectToWork()
{
    var repositoryMock = new Mock<IDummyRepository>();
    var serviceDummy = new ServiceDummy(repositoryMock.Object);
    var entity = new Dummy { DummyString = "DummyString" };

    repositoryMock.Setup(i => i.Add(It.IsAny<Dummy>())).Verifiable();

    serviceDummy.Add(entity);
    repositoryMock.Verify();
 }

抱歉,我刚刚发现问题,这是我的GenericRepository代码中的错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM