How to unit test abstract classes: extend with stubs?

后端 未结 14 1779
有刺的猬
有刺的猬 2020-11-27 08:37

I was wondering how to unit test abstract classes, and classes that extend abstract classes.

Should I test the abstract class by extending it, stubbing out the abstr

14条回答
  •  忘掉有多难
    2020-11-27 09:30

    One of the main motivations for using an abstract class is to enable polymorphism within your application -- i.e: you can substitute a different version at runtime. In fact, this is very much the same thing as using an interface except the abstract class provides some common plumbing, often referred to as a Template pattern.

    From a unit testing perspective, there are two things to consider:

    1. Interaction of your abstract class with it related classes. Using a mock testing framework is ideal for this scenario as it shows that your abstract class plays well with others.

    2. Functionality of derived classes. If you have custom logic that you've written for your derived classes, you should test those classes in isolation.

    edit: RhinoMocks is an awesome mock testing framework that can generate mock objects at runtime by dynamically deriving from your class. This approach can save you countless hours of hand-coding derived classes.

提交回复
热议问题