MSTest - 带有list参数的Moq设置返回空列表

时间:2016-04-25 11:50:02

标签: c# unit-testing mocking moq mstest

我有这样的事情:

WebRequestManagerMock
    .Setup(x => x.GetItemsAsync(It.IsAny<IEnumerable<Order>>()))
    .Returns<IEnumerable<Order>>(orders => Task.FromResult<IEnumerabe<Item>>(m_Items.Take(orders.Count())));

m_Items是我填写Class Initialize的静态列表,不是空的。

调试测试时,

Orders也不为空。

当我致电GetItemsAsync时,无论有多少订单,我都会得到0件商品。

模拟也是静态的。

我做错了吗?

2 个答案:

答案 0 :(得分:1)

显然我是瞎子。我没注意到我在TestInitialize方法中创建了我的mock的新实例。感谢您告诉我问题出在我的代码中,而不是moq。

答案 1 :(得分:0)

我为您的场景重新创建了Minimal, Complete, and Verifiable example测试,并且能够让它通过。看看下面的

[TestClass]
public class MoqSetupWithListParameterTests : MiscUnitTests {
    //m_Items is a static list I filled in the Class Initialize, and is not empty. 
    static IEnumerable<Item> m_Items = Enumerable.Range(1, 10).Select(i => new Item());
    //The mock is also static. 
    static Mock<IWebRequestManager> WebRequestManagerMock = new Mock<IWebRequestManager>();

    [TestMethod]
    public void Items_Count_Should_Equal_Orders_Count() {
        //Arrange
        var expected = 3;
        //Orders is also not empty when I debug the test.
        var m_Orders = Enumerable.Range(1, expected).Select(i => new Order());
        WebRequestManagerMock
            .Setup(x => x.GetItemsAsync(It.IsAny<IEnumerable<Order>>()))
            .Returns<IEnumerable<Order>>(orders => Task.FromResult(m_Items.Take(orders.Count())));

        var sut = WebRequestManagerMock.Object;

        //Act
        //When I call GetItemsAsync I get expected count.
        var actual = sut.GetItemsAsync(m_Orders).Result;

        //Assert
        Assert.AreEqual(expected, actual.Count());
    }

    public interface IWebRequestManager {
        Task<IEnumerable<Item>> GetItemsAsync(IEnumerable<Order> enumerable);
    }

    public class Order { }
    public class Item { }
}