Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test abstract classes

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.

like image 775
ediblecode Avatar asked Nov 01 '11 12:11

ediblecode


People also ask

Can you unit test an abstract class?

Summary. There are two ways to unit test a class hierarchy and an abstract class: Using a test class per each production class. Using a test class per concrete production class.

Can you test an abstract class in Java?

You can not test whole abstract class. In this case you have abstract methods, this mean that they should be implemented by class that extend given abstract class.

How do I test an abstract class in Python?

There are two options to test an abstract base class (ABC) in Python: you can either override or patch the __abstractmethods__ property to be able to instantiate the abstract class and test it directly or you can create a child class that implements all the abstract methods of the base class.

Can we mock an abstract class?

mock() method for mocking the abstract classes. Using PowerMock instead of Mockito. mock() is a better approach as it can have control over the private as well as static methods. Step1: Create an abstract class named Abstract_class that contains both abstract and non-abstract methods.


1 Answers

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.

like image 177
sloth Avatar answered Sep 24 '22 19:09

sloth