How to unit test abstract classes

2019-06-14 20:52发布

Used the create unit tests tool in Visual Studio and obviously it tries to instantiate my abstract classes.

My question is: Should I try to unit test the way Visual Studio is trying to get me to do it, or should I create a mock class to be instantiated, or should I only test the methods that use this abstract class?

Thanks.

4条回答
太酷不给撩
2楼-- · 2019-06-14 21:23

There are two opposite points of view:

  • Do not test abstract class itself, test concrete classes inherited from it
  • Abstract class should be tested as well because provides some built in logic shared across all the inherited classes so you just test base logic in abstract class once

I prefer second option (currently) and testing abstract classes using RhinoMocks PartialMock feature which allows me to create a mock of an abstract class.

查看更多
做个烂人
3楼-- · 2019-06-14 21:24

use from mockrepository :

[testmethod]
       public void testwithmockrepository()
       {
           var mockrepository = new rhino.mocks.mockrepository();
           var mock = mockrepository.partialmock<myabstractclass>();

           using ( mockrepository.record() )
           {
               expect.call( mock.dosomething( arg<string>.is.anything ) ).return( "hi..." ).repeat.once();
           }
           using ( mockrepository.playback() )
           {
               assert.areequal( "hi..." , mock.dosomething( "salam" ) );
           }
       }
查看更多
时光不老,我们不散
4楼-- · 2019-06-14 21:36
  1. Just test the implementing classes.

  2. You could always create a specific implementation for testing that adds no extra functionality.

  3. Listen to the tests. Using mocking tools that do magic to allow testing abstract classes and private methods etc. are a test code smell

查看更多
来,给爷笑一个
5楼-- · 2019-06-14 21:39

If there are methods on this abstract class that are worth testing, then you should test them. You could always subclass the abstract class for the test (and name it like MyAbstractClassTesting) and test this new concrete class.

查看更多
登录 后发表回答