使用Moq验证私有方法的执行 [英] Using Moq to verify execution of private methods

查看:106
本文介绍了使用Moq验证私有方法的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试以下逻辑(这显然是我方法的简化版本):

I want to test the following logic (this is obviously a stripped-down version of my method):

public void myPublicMethod(params) {

    if(some_condition)
        privateMethod1();
    else
        privateMethod2();
} 

我已经模拟了方法中的所有其他依赖项,并且已经进行了设置,以便可以保证some_condition为true.我想做的是验证我的privateMethod1()刚被调用一次,而privateMethod2()根本没有被调用. Moq可以做到这一点吗?

I have all of the other dependencies in the method mocked out, and I've set this up so that I can guarantee that some_condition is true. What I want to do is verify that my privateMethod1() is called exactly once, and privateMethod2() is not called at all. Is this possible to do with Moq?

以下是有关此问题的一些说明:

Here are some notes on the issue:

  • privateMethod1()和privateMethod2()与myPublicMethod属于同一类,因此我无法为此类创建模拟对象.
  • privateMethod1/2的主体都包含来自包含这些类和myPublicMethod的类的许多依赖关系,因此将privateMethod1/2分解为自己的帮助器类将非常耗时

有什么想法吗?提前致谢.我愿意接受无法做到这一点,但我想知道一种或另一种方式.

Any thoughts? Thanks in advance. I'm willing to accept that this can't be done, but I'd like to know one way or another.

推荐答案

不要测试私有方法.它们是该类的私有实现细节.您应该只测试执行公共方法的结果.只要您的结果能按预期出来,就不必在意如何获得结果.

Don't test private methods. They are private implementation details of the class. You should only test the results of executing public methods. As long as your results come out as expected, you shouldn't care how the result is obtained.

在私有方法上构建测试将导致脆弱的测试,当您重构私有实现时(出于性能或其他原因),这些测试很容易破坏.

Building tests on private methods will lead to brittle tests that break easily when you refactor private implementations (for performance or other reasons).

这篇关于使用Moq验证私有方法的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆