验证方法已被调用的IEnumerable含有“X”用起订量元素 [英] Verify method has been called with IEnumerable containing 'x' elements with Moq

查看:97
本文介绍了验证方法已被调用的IEnumerable含有“X”用起订量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Add方法接受一个I​​Enumerable的作为参数的存储库:

I have a repository with an Add method that takes an IEnumerable as parameter:

public void Add<T>(T item) where T : class, new(){}

在一个单元测试我要验证此方法被调用,它包含的元素作为另一个的IEnumerable

In a unittest I want to verify that this method is called with an IEnumerable that contains exactly the same amount of elements as another IEnumerable

[Test]
public void InvoicesAreGeneratedForAllStudents()
{
    var students = StudentStub.GetStudents();
    session.Setup(x => x.All<Student>()).Returns(students.AsQueryable());

    service.GenerateInvoices(Payments.Jaar, DateTime.Now); 

    session.Verify(x => x.Add(It.Is<IEnumerable<Invoice>>(
        invoices => invoices.Count() == students.Count())));
 }

单元测试的结果:

Result of the unit test:

Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: 

x => x.Add<Invoice>(It.Is<IEnumerable`1>(i => i.Count<Invoice>() == 10))

No setups configured.

我是什么做错了吗?

What am I doing wrong?

推荐答案

从你的code例如,你有没有设置在x => x.Add的起订量

From your code example you haven't set up the x => x.Add on the Moq

session.Setup(x => x.Add(It.IsAny<IEnumerable>());

除非安装了x.All,就是要x.Add?如果是这样,你需要匹配的验证和设置完全相同 - 一个很好的方式来做到这一点是将其解压缩到一个返回前pression的常用方法

Unless the Setup for x.All is meant to be x.Add? If so, you need to match the Verify and Setup exactly - a good way to do that is to extract it to a common method that returns an Expression.

编辑:增加了一个样品,我已经改变了添加签名,因为我看不出你如何能传递一个集合否则

Added a sample, I have changed the signature of Add as I can't see how you could pass a collection otherwise.

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mock<Boo> moqBoo = new Mock<Boo>();
        moqBoo.Setup(IEnumerableHasExpectedNumberOfElements(10));

        // ACT

        moqBoo.Verify(IEnumerableHasExpectedNumberOfElements(10));
    }

    private static Expression<Action<Boo>> IEnumerableHasExpectedNumberOfElements(int expectedNumberOfElements)
    {
        return b => b.Add(It.Is<IEnumerable<Invoice>>(ie => ie.Count() == expectedNumberOfElements));
    }
}

public class Boo
{
    public void Add<T>(IEnumerable<T> item) where T : class, new()
    {
    }
}

public class Invoice
{

}

此外,调试这些事情的好办法是用MockBehavior.Strict设置您的模拟了,然后你会通过调用code你需要配置通知。

Also, a good way to debug these things is to set your Mock up with MockBehavior.Strict and then you'll be informed by the invoked code what you need to configure.

这篇关于验证方法已被调用的IEnumerable含有“X”用起订量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆