How to unit test abstract classes: extend with stubs?

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

    First if abstract class contained some concrete method i think you should do this considered this example

     public abstract class A 
    
     {
    
        public boolean method 1
        {
            // concrete method which we have to test.
    
        }
    
    
     }
    
    
     class B extends class A
    
     {
    
          @override
          public boolean method 1
          {
            // override same method as above.
    
          }
    
    
     } 
    
    
      class Test_A 
    
      {
    
        private static B b;  // reference object of the class B
    
        @Before
        public void init()
    
          {
    
          b = new B ();    
    
          }
    
         @Test
         public void Test_method 1
    
           {
    
           b.method 1; // use some assertion statements.
    
           }
    
       }
    
    0 讨论(0)
  • 2020-11-27 09:38

    I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.

    As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.

    0 讨论(0)
提交回复
热议问题