James
James

Reputation: 553

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?

Upvotes: 1

Views: 977

Answers (1)

Guillaume S.
Guillaume S.

Reputation: 1545

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);

Upvotes: 2

Related Questions