[英]Mocking a list of objects
I'm learning how to write unit tests and am a little stuck on using Mocks. 我正在学习如何编写单元测试,并且在使用Mocks方面有些卡住。 I'm using Moq for mocking. 我正在使用Moq进行模拟。 I am using the built in test framework that comes with VS 2012. I can switch to NUnit if that is better (and would solve my problem). 我使用的是VS 2012随附的内置测试框架。如果这样更好(可以解决我的问题),则可以切换到NUnit。 I have a unit of work pattern setup. 我有一个工作模式设置单元。 The method I'm testing is for resetting a user's password. 我正在测试的方法是重置用户密码。 I am telling Moq to return a list of users based on a unique code which is what is called in the method I'm testing: 我告诉Moq根据唯一的代码返回用户列表,这就是我正在测试的方法中所称的代码:
var mock = new Mock<IUnitOfWork>();
mock.Setup(u => u.UserRepository.Get(t => t.PassResetCode.Equals("test1"), null, "")).Returns(
new List<User>
{
new User { UserId = 4, FirstName = "Test4", LastName = "LastName", Email = "test4@test.com", Salt = salt, Password = pass, AccountConfirmed = true, PassResetCode = "test1", PassResetExpire = new Nullable<DateTime>(DateTime.Now.Add(ts)) },
});
In the method I'm testing it calls the following: 在我测试的方法中,它调用以下内容:
var users = unitOfWork.UserRepository.Get(u => u.PassResetCode.Equals(code));
As far as I can tell, it is not returning the list of users I'm creating in the test here. 据我所知,这里没有返回我在测试中创建的用户列表。 Do I need to mock the repository too that is within the Unit of work class? 我是否也需要模拟工作单元类中的存储库? Or is just mocking the unit of work interface enough? 还是仅嘲笑工作单元界面就足够了? I can post more of the code if that helps. 如果有帮助,我可以发布更多代码。
Your repository accepts delegate and you're setting an expectation to expect particular delegate t => t.PassResetCode.Equals("test1")
. 您的存储库接受委托,并且您正在设置期望特定的委托t => t.PassResetCode.Equals("test1")
。 I think mock inside will compare the passed predicate to this delegate. 我认为模拟内部会将传递的谓词与此委托进行比较。 Different delegate instances will not match with 99.99% probability. 不同的委托实例将不具有99.99%的概率匹配。 You should probably avoid setting up specific constraint for predicate in this particular expectation and use It.IsAny<>()
instead. 您可能应该避免在此特定期望中为谓词设置特定约束,而应使用It.IsAny<>()
。
var mock = new Mock<IUnitOfWork>();
mock.Setup(It.IsAny<Func<User, bool>>(), null, ""), ...).Returns(...)
var mock = new Mock<IUnitOfWork>();
mock.Setup(u => u.UserRepository.Get("test1", null, "")).Returns(
new List<User>
{
new User { UserId = 4, FirstName = "Test4", LastName = "LastName", Email = "test4@test.com", Salt = salt, Password = pass, AccountConfirmed = true, PassResetCode = "test1", PassResetExpire = new Nullable<DateTime>(DateTime.Now.Add(ts)) },
});
You have to be sure you are passing exactly those parameters. 您必须确保要完全传递这些参数。 Or you can use the syntax It.IsAny<TYPE>()
for any parameter you do not care. 或者,可以对It.IsAny<TYPE>()
的任何参数使用语法It.IsAny<TYPE>()
。 Or you can do It.Is<TYPE>(condition)
to check for the parameter. 或者您可以执行It.Is<TYPE>(condition)
以检查参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.