简体   繁体   English

如何用Moq测试void方法?

[英]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 ,我将进行以下测试:

  1. Assert GetSomething() was called on mocked userDAO userDAO调用了断言GetSomething()
  2. Assert returned reference string cod == passed in User.Cod that we used to create mocked userDAO 声明返回的参考字符串cod ==传入了我们用来创建userDAO
  3. Assert returned reference string 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: 我通常建议尽量避免使用它们,但是当您需要测试一个时,一般的经验法则是:

  1. Assert all expected calls on your mocks were made. 确认对您的模拟进行了所有预期的呼叫。
  2. If possible, assert that the mocks were called with specific parameter values. 如果可能,断言使用特定的参数值调用了模拟。 This is more important for void methods, because you are testing the side-effects. 这对于void方法更为重要,因为您正在测试副作用。
  3. Assert every side-effect you can, including those that should not have changed. 声明所有可能的副作用,包括那些不应该改变的副作用。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM