Cant Mock my Get() function from my repository - MongoDB.Driver 2.2.3

风流意气都作罢 提交于 2019-12-04 20:16:14

Yes, you need to mock IFindFluent. Let me show you an example.

I used NUnit and Moq for tests, driver version is 2.2.3.

public interface IRepository
{
    IFindFluent<TEntity, TEntity> GetFluent<TEntity>(Expression<Func<TEntity, bool>> filter = null)
        where TEntity : class, new();
}

public class LocationService
{
    public long CountLocations(IRepository repository)
    {
        return repository.GetFluent<Location>(location => true).Count();
    }
}

[TestFixture]
public class LocationServiceTests
{
    [Test]
    public void CountLocationsTest()
    {
        const long LocationCount = 5;

        var locationsMock = new Mock<IFindFluent<Location, Location>>();
        locationsMock.Setup(x => x.Count(default(CancellationToken))).Returns(LocationCount);

        var repoMock = new Mock<IRepository>();
        repoMock.Setup(repo => repo.GetFluent(It.IsAny<Expression<Func<Location, bool>>>()))
                .Returns(locationsMock.Object);

        var locationService = new LocationService();
        long result = locationService.CountLocations(repoMock.Object);

        Assert.AreEqual(LocationCount, result);
    }
}

Good answer from Usein Mambediev. There is an similar example, how to mock IFindFluent with Typemock Isolator without wrapping it into the interface:

 [TestMethod, Isolated]
 public void TestGet()
 {
     var target = new ClassUnderTest();
     var returnMock = Isolate.Fake.Instance<IFindFluent<Location, Location>>();

     int size = 3;

     Isolate.WhenCalled(() => returnMock.Count()).WillReturn(size);
     Isolate.WhenCalled(() => target.GetFluent(default(Expression<Func<Location, bool>>))).WillReturn(returnMock);

     Assert.AreEqual(size, target.GetFluent<Location>(location => true).Count());
}

I've put your method into the public class just in order to test. You only need to change the target. Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!