使用附加的Where()表达式模拟IRavenQueryable

man*_*eko 12 c# unit-testing moq mocking ravendb

我正在尝试为新的mvc3项目做一些概念类型代码的基本证明.我们正在使用Moq和RavenDB.

行动:

public ActionResult Index(string id)
{
    var model = DocumentSession.Query<FinancialTransaction>()
        .Where(f => f.ResponsibleBusinessId == id);
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

测试:

private readonly Fixture _fixture = new Fixture();

[Test]
public void Index_Action_Returns_List_Of_FinancialTransactions_For_Business([Random(0, 50, 5)]int numberOfTransactionsToCreate)
{
    // Arrange
    var session = new Mock<IDocumentSession>();
    var financialController = new FinancialController { DocumentSession = session.Object };

    var businessId = _fixture.CreateAnonymous<string>();
    var transactions = _fixture.Build<FinancialTransaction>()
        .With(f => f.ResponsibleBusinessId, businessId)
        .CreateMany(numberOfTransactionsToCreate);

    // Mock
    var ravenQueryableMock = new Mock<IRavenQueryable<FinancialTransaction>>();
    ravenQueryableMock.Setup(x => x.GetEnumerator()).Returns(transactions.GetEnumerator);
    ravenQueryableMock.Setup(x => x.Customize(It.IsAny<Action<Object>>()).GetEnumerator()).Returns(() => transactions.GetEnumerator());

    session.Setup(s => s.Query<FinancialTransaction>()).Returns(ravenQueryableMock.Object).Verifiable(); 

    // Act
    var actual = financialController.Index(businessId) as ViewResult;

    // Assert
    Assert.IsNotNull(actual);
    Assert.That(actual.Model, Is.InstanceOf<List<FinancialTransaction>>());

    var result = actual.Model as List<FinancialTransaction>;
    Assert.That(result.Count, Is.EqualTo(numberOfTransactionsToCreate));
    session.VerifyAll();
}
Run Code Online (Sandbox Code Playgroud)

看起来问题出在.Where(f => f.ResponsibleBusinessId == id).从模拟的IRavenQueryable,我返回一个FinancialTransactions列表,所以人们会认为.Where()会根据它进行过滤.但是因为它是IQueryable,我猜它正在尝试将表达式全部作为一个执行,当它枚举时.

为了验证,我将操作的查询更改为:

var model = DocumentSession.Query<FinancialTransaction>()
    .ToList()
    .Where(f => f.ResponsibleBusinessId == id);
Run Code Online (Sandbox Code Playgroud)

这确实让测试通过,但是,它并不理想,因为这意味着它将枚举所有记录,然后过滤它们.

有没有办法让Moq使用它?

Arn*_*kas 9

正如评论中所提到的,您不应该在测试中模拟RavenDB API.

由于InMemory模式,RavenDB对单元测试提供了出色的支持:

[Test]
public void MyTest()
{
    using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })
    {
        documentStore.Initialize();

        using (var session = documentStore.OpenSession())
        {
            // test
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的机器上加载和初始化Raven嵌入式服务器需要将近3秒钟.这是一个不可接受的时间来添加到单元测试. (7认同)

Jon*_*ams 5

正如其他人所提到的,如果您可以使用内存/嵌入式模式,那么它非常适合集成测试。但在我看来,单元测试不够快或不够容易。

我找到了Sam Ritchie的一篇博客文章,它为IQueryableIRavenQueryable提供了一个“假的”(标准 LINQ 的包装器),用于此类情况。他的有点过时了,因为较新版本的 Raven(当前为 2.5)在IRavenQueryable界面上提供了一些额外的方法。我目前不使用这些新方法 ( TransformWith, AddQueryInput, Spatial),所以我现在只是懒洋洋地留NotImplementedException在下面的代码中。

有关我基于此的原始代码以及使用示例,请参阅Sam 的帖子

public class FakeRavenQueryable<T> : IRavenQueryable<T> {
    private readonly IQueryable<T> source;

    public FakeRavenQueryable(IQueryable<T> source, RavenQueryStatistics stats = null) {
        this.source = source;
        this.QueryStatistics = stats;
    }

    public RavenQueryStatistics QueryStatistics { get; set; }

    public Type ElementType {
        get { return typeof(T); }
    }

    public Expression Expression {
        get { return this.source.Expression; }
    }

    public IQueryProvider Provider {
        get { return new FakeRavenQueryProvider(this.source, this.QueryStatistics); }
    }

    public IRavenQueryable<T> Customize(Action<IDocumentQueryCustomization> action) {
        return this;
    }

    public IRavenQueryable<TResult> TransformWith<TTransformer, TResult>() where TTransformer : AbstractTransformerCreationTask, new() {
        throw new NotImplementedException();
    }

    public IRavenQueryable<T> AddQueryInput(string name, RavenJToken value) {
        throw new NotImplementedException();
    }

    public IRavenQueryable<T> Spatial(Expression<Func<T, object>> path, Func<SpatialCriteriaFactory, SpatialCriteria> clause) {
        throw new NotImplementedException();
    }

    public IRavenQueryable<T> Statistics(out RavenQueryStatistics stats) {
        stats = this.QueryStatistics;
        return this;
    }

    public IEnumerator<T> GetEnumerator() {
        return this.source.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return this.source.GetEnumerator();
    }
}

public class FakeRavenQueryProvider : IQueryProvider {
    private readonly IQueryable source;

    private readonly RavenQueryStatistics stats;

    public FakeRavenQueryProvider(IQueryable source, RavenQueryStatistics stats = null) {
        this.source = source;
        this.stats = stats;
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression) {
        return new FakeRavenQueryable<TElement>(this.source.Provider.CreateQuery<TElement>(expression), this.stats);
    }

    public IQueryable CreateQuery(Expression expression) {
        var type = typeof(FakeRavenQueryable<>).MakeGenericType(expression.Type);
        return (IQueryable)Activator.CreateInstance(type, this.source.Provider.CreateQuery(expression), this.stats);
    }

    public TResult Execute<TResult>(Expression expression) {
        return this.source.Provider.Execute<TResult>(expression);
    }

    public object Execute(Expression expression) {
        return this.source.Provider.Execute(expression);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 抱歉……我真正想说的是“这个答案应该放在最前面,因为真正的单元测试应该设计为在短时间内运行……”。不要进入整个单元测试与集成测试的事情(并注意到 Ayende 似乎已经将他的位置转向集成测试,而不是单元测试加上模拟或假货),但我是这样看待它的,虽然我对人们没问题在这方面做他们想做的任何事情,问题是询问起订量,因此该人采用(真实的)单元测试方法 - 所以你的答案应该是首选(即使它是假的而不是模拟的)。 (2认同)
  • 另一个注意事项,如果您使用异步 api,`IQueryProvider` 的实现将不起作用。诸如 `.ToListAsync()` 之类的 Raven 扩展方法抱怨查询提供程序不是一个 `IRavenQueryProvider` (2认同)