How to unit test abstract classes: extend with stubs?

后端 未结 14 1786
有刺的猬
有刺的猬 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:26

    This is the pattern I usually follow when setting up a harness for testing an abstract class:

    public abstract class MyBase{
      /*...*/
      public abstract void VoidMethod(object param1);
      public abstract object MethodWithReturn(object param1);
      /*,,,*/
    }
    

    And the version I use under test:

    public class MyBaseHarness : MyBase{
      /*...*/
      public Action VoidMethodFunction;
      public override void VoidMethod(object param1){
        VoidMethodFunction(param1);
      }
      public Func MethodWithReturnFunction;
      public override object MethodWithReturn(object param1){
        return MethodWihtReturnFunction(param1);
      }
      /*,,,*/
    }
    
    
    

    If the abstract methods are called when I don't expect it, the tests fail. When arranging the tests, I can easily stub out the abstract methods with lambdas that perform asserts, throw exceptions, return different values, etc.

    提交回复
    热议问题