单元测试以验证是否调用了基类方法 [英] Unit test to verify that a base class method is called

查看:69
本文介绍了单元测试以验证是否调用了基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类:

public abstract class MyBaseClass
{
    protected virtual void Method1()
    {    
    }
} 

和派生类:

public class MyDerivedClass : MyBaseClass
{
    public void Method2()
    {
        base.Method1();
    }
}

我想为Method2编写一个单元测试,以验证它是否在基类上调用了Method1.我正在使用Moq作为模拟库.这可能吗?

I want to write a unit test for Method2 to verify that it calls Method1 on the base class. I'm using Moq as my mocking library. Is this possible?

我遇到了一个相关的SO链接:

I came across a related SO link:

用Moq模拟基类方法调用

其中第二个答案建议可以通过在模拟对象上将CallBase属性设置为true来实现.但是,尚不清楚如何验证对基类方法(在上例中为Method1)的调用.

in which the 2nd answer suggests it can be achieved by setting CallBase property to true on the mock object. However it's not clear how this would enable the call to the base class method (Method1 in the above example) to be verified.

对此表示感谢.

推荐答案

单元测试应验证行为,而不是实现.造成这种情况的原因有很多:

Unit tests should verify behavior, not implementation. There are several reasons for this:

  • 结果是目标,而不是您获得结果的方式
  • 测试结果使您无需重新编写测试即可改善实施
  • 难以模拟实施
  • The results are the goal, not how you get the results
  • Testing results allows you to improve the implementation without re-writing your tests
  • Implementations are harder to mock

可能可以置入钩子或创建模拟程序以验证是否调用了基本方法,但是您是否真的在乎如何达到答案,还是您是否在乎答案是正确?

You might be able to put in hooks or create mocks that verify that the base method was called, but do you really care how the answer was achieved, or do you care that the answer is right?

如果您需要的特定实现具有可以验证的副作用,则 是您应验证的内容.

If the particular implementation you require has side effects that you can verify, then that is what you should be validating.

这篇关于单元测试以验证是否调用了基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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