如何使用 Moq 测试 void 方法?
我是 TDD 新手,我仍然有很多问题,其中一个问题是如何测试 void 方法!
我有这个参数通过引用传递的参数,我不知道如何测试:(这只是一个测试,不是我真正的方法)
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;
}
}
有人可以帮忙吗?谢谢!
Im new at TDD and i still have many questions, and one of this questions is how to test a void method!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设
userDAO
作为依赖项注入并且可以被模拟,我将进行以下测试:userDAO
上调用断言GetSomething()
cod
== 传入我们的 User.Cod用于创建模拟的
userDAO
name
== 传入 User.Cod 中我们曾经创建模拟的
userDAO
我同意避免 ref 参数,但我建议按照 @Tim Cools 的其他答案中的建议进行重构
Assuming
userDAO
was injected as a dependency and can be mocked I would do the following tests:GetSomething()
was called on mockeduserDAO
cod
== passed in User.Cod that weused to create mocked
userDAO
name
== passed in User.Cod thatwe used to create mocked
userDAO
I agree with avoiding ref parameters though, I would suggest refactoring as suggested in the other answer by @Tim Cools
你应该尽量避免 ref 和 out参数。 使用包含这两个属性的对象。这将使你的设计更清晰,你的工作更清晰...
编辑:如果你真的想最小起订量输出参数使用,你可以找到一个例子 此处
you should try to avoid ref and out parameters. 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
只需在调用方法后测试参数中的值,模拟 userDAO 来控制它返回的内容(null、cod、name)
Just test the values in the params after you call the method, mocking the userDAO to control what it returns (null, cod, name)
void 方法意味着将会有某种副作用。我通常建议如果可能的话避免使用它们,但是当您确实需要测试它们时,一般经验法则是:
实际上,这些断言也应该针对非 void 方法,也许更多的是为了防止意外的副作用,而不是测试预期的副作用。 (IMO,如果可能的话,函数应该具有零副作用。)
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.)