简体   繁体   English

如何对抽象类的虚拟方法进行单元测试?

[英]How to unit test a virtual method on an abstract class?

I've got a C# abstract class which has behavior in a virtual method. 我有一个C#抽象类,该类在虚拟方法中具有行为。 I need to unit test that behavior in that virtual method (not in question: when that method gets called). 我需要对该虚拟方法中的行为进行单元测试(没有问题:何时调用该方法)。 I see three options: 我看到三个选择:

1) create a dummy implementation of the abstract class 1)创建抽象类的虚拟实现
2) use the children to call the virtual method (duplicated tests per child implementation) 2)使用子代调用虚拟方法(每个子代实现重复测试)
3) another option someone here points out 3)这里有人指出的另一种选择

I'm leaning toward #1. 我倾向于#1。 Is that the smartest way to test this behavior? 这是测试此行为的最明智的方法吗?

Ideally you want to test just that class , so create a dummy implementation. 理想情况下,您只想测试该类 ,因此创建一个虚拟实现。 If you're using a mocking framework which supports mocking classes, that's probably the easiest way of doing it. 如果您使用的是支持模拟类的模拟框架,那可能是最简单的方法。 If your virtual method calls abstract (or virtual) methods defined in the abstract class, the mocking framework will allow you to validate that those calls occur. 如果您的虚拟方法调用了抽象类中定义的抽象(或虚拟)方法,则模拟框架将允许您验证发生了这些调用。 (On the other hand, you may wish to use the mocking framework to create a stub , if you're more interested in the results than in testing the exact protocol involved between the abstract class and its children.) (另一方面,如果您对结果比对测试抽象类及其子类之间的确切协议更感兴趣,则可能希望使用模拟框架来创建存根 。)

I personally always create duplicate tests per child implementation. 我个人总是为每个子实现创建重复的测试。 This way if anyone comes and overrides the method in a child class you will break tests and know that they need to be re-written. 这样,如果有人来覆盖子类中的方法,您将中断测试并知道需要重写它们。 Just a little extra coverage. 只需一点额外的覆盖。

Ultimately, you should question why the base class needs to implement a new default implementation. 最终,您应该质疑为什么基类需要实现新的默认实现。 Maybe you should be delegating? 也许您应该委派? Why are you modifying behavior that impacts all classes? 为什么要修改影响所有班级的行为?

But if you must modify behavior that all children should inherit... 但是如果您必须修改所有孩子都应该继承的行为...

Combine 1 and 2. Test using a dummy as a control test. 组合1和2。使用假人作为对照测试。

Then test using at least 1 practical usage of the behavior to make sure it works with an actual case. 然后,至少使用该行为的一种实际用法进行测试,以确保该行为与实际情况相符。

Developers writing the children are responsible for their behavior. 编写孩子的开发人员应对他们的行为负责。

Ultimately someone should be sure it works with all existing children before release so you're not damaging those children, but if you've proven the base class implementation is valid, then any changes should be from those objects that extend the base class. 最终,应该有人确保发布前它可以与所有现有子级一起使用,因此您不会损坏那些子级,但是如果您已证明基类实现是有效的,则所有更改都应该来自扩展基类的那些对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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