我有这样的事情:
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件商品。
模拟也是静态的。
我做错了吗?
答案 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 { }
}