简体   繁体   中英

Mocked interface is returning null

I'm pretty new with using Moq and I'm running into an issue were one of my method calls is returning null despite the fact that I have mocked it.

I am mocking the following interfaces.

public interface IUnitOfWorkFactory
{
    IUnitOfWork Create(KnownDbContexts knownDbContexts);
}

public interface IUnitOfWork : IDisposable
{
    Task SaveChanges();

    IRepository Repository { get; }
}

Then in my unit test code it looks like this.

_uowFactoryMock.Setup(x => x.Create(It.IsAny<KnownDbContexts>()))
            .Returns(It.IsAny<IUnitOfWork>());

The code I'm testing looks like this.

using (var uow = _unitOfWorkFactory.Create(KnownDbContexts.UserDefined1))
{
    // At this point 'uow' is null.
}

Why is IUnitOfWorkFactory.Create returning null?

In your current code, the method Create of the mocked factory returns an object of type It.IsAny<IUnitOfWork> .

However you want your mocked factory to return a mock of the unit of work, as such:

var uowMock = new Mock<IUnitOfWork>();
// here mock uowMock's methods (ie SaveChanges) in the same way it is done below for the factory

_uowFactoryMock.Setup(x => x.Create(It.IsAny<KnownDbContexts>()))
        .Returns(uowMock.Object);

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