[英]How to test a void method with Moq?
Im new at TDD and i still have many questions, and one of this questions is how to test a void method! 我是TDD的新手,我还有很多问题,其中一个问题是如何测试void方法!
I have this one with params passed by refference, and i have no clue how to test: (this is just a test, not my real method) 我有一个通过引用传递的参数,并且我不知道如何测试:(这只是测试,不是我的真实方法)
public void ReplaceCenter(ref string cod, ref string name)
{
User user = userDAO.GetSomething();
if (user.Cod != null)
{
cod = user.Cod;
}
if (user.Name != null)
{
name = user.Name;
}
}
Can someoen help? 可以帮忙吗? Thanks!
谢谢!
Assuming userDAO
was injected as a dependency and can be mocked I would do the following tests: 假设将
userDAO
作为依赖项注入并且可以被userDAO
,我将进行以下测试:
GetSomething()
was called on mocked userDAO
userDAO
调用了断言GetSomething()
cod
== passed in User.Cod that we used to create mocked userDAO
cod
==传入了我们用来创建userDAO
name
== passed in User.Cod that we used to create mocked userDAO
name
==传入了我们用来创建userDAO
I agree with avoiding ref parameters though, I would suggest refactoring as suggested in the other answer by @Tim Cools 我同意避免使用ref参数,但我建议按照@Tim Cools的其他答案中的建议进行重构
you should try to avoid ref and out parameters. 您应该尝试避免使用ref和out参数。 use an object that contains the two properties.
使用包含两个属性的对象。 this would make your design cleaner and your job much cleaner...
这将使您的设计更加整洁,工作更加整洁...
edit: if you really want to moq the out parameters use you can find an example here 编辑:如果您确实想使用out参数,可以在此处找到示例
调用方法后,只需测试params中的值,即可模拟userDAO以控制其返回值(空,鳕鱼,名称)
A void method implies that there is going to be some sort of side-effect. 无效方法意味着会有某种副作用。 I generally suggest avoiding them, if possible, but when you do need to test one, general rules of thumb would be:
我通常建议尽量避免使用它们,但是当您需要测试一个时,一般的经验法则是:
Really, these assertions should be made for non-void methods, as well, perhaps more to prevent unexpected side-effects than to test for expected ones. 实际上,这些断言也应该针对非无效方法进行,也许更多的是要防止意外的副作用,而不是测试预期的副作用。 (IMO, a function should have zero side-effects if at all possible.)
(IMO,如果有可能,函数应具有零副作用。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.