开发者

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. 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

2) use the children to call the virtual method (duplicated tests per child implementation)

3) another opti开发者_如何学Goon someone here points out

I'm leaning toward #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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜