2016-03-09 25 views
1

在我的單元測試中,我想測試我創建的用於從MongoDB過濾數據的方法。無法模仿我的存儲庫中的Get()函數 - MongoDB.Driver 2.2.3

當我嘗試嘲笑我的功能是這樣的:

_repo.GetFluent<Location>((Arg.Any<Expression<Func<Location, bool>>>())) 
       .Returns(x => locations.Where(x.Arg<Expression<Func<Location, bool>>>()).ToList()); 

它強調的Returns說:

無法轉換lambda表達式。

時,我曾在我的簡單的項目使用MongoDB的2.0.0驅動我沒有問題,我的嘲諷功能Get()這樣的,但現在新的2.2.3驅動程序之前我有一個錯誤嘲笑他。有另一種方法嗎?

我已經看到,新的驅動程序正在使用IFindFluent,而舊的驅動程序使用了MongoCursor來獲取我的數據。

我應該嘲笑IFindFluent莫名其妙嗎?

這是我爲GetFluent()方法

public IFindFluent<TEntity, TEntity> GetFluent<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null) where TEntity : class, new() 
     { 
      var collection = GetCollection<TEntity>(); 
      if (filter == null) 
      { 
       var emptyFilter = Builders<TEntity>.Filter.Empty; 
       return collection.Find(emptyFilter); 
      } 
      else 
      { 
       var filterDefinition = Builders<TEntity>.Filter.Where(filter); 
       return collection.Find(filterDefinition); 
      } 
     } 
+0

你可以粘貼你的MongoRepository的GetFluent方法的代碼嗎? – Jerome2606

回答

0

是的,你需要模擬IFindFluent代碼。讓我給你看一個例子。

我用NUnit和Moq進行測試,驅動版本是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); 
    } 
} 
0

Usein Mambediev很好的回答。有一個類似的例子,如何用Typemock Isolator嘲笑IFindFluent不包成接口:

[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()); 
} 

我已經把你的方法爲公共類只是爲了測試。你只需要改變目標。 祝你好運!

相關問題