I have to develop JUnit test cases for application which has several abstract classes and methods. Is is possible to create JUnit test cases for the abstract classes without being extended by another class? If a subclass extends an abstract class, is it enough to test the subclass? How to create test cases for non abstract methods of abstract class?
-
1Do you want to create test cases for non abstract methods of abstract calss? – Despicable May 21 '13 at 09:46
-
1see this question http://stackoverflow.com/questions/1087339/using-mockito-to-test-abstract-classes I hope it will help you – Freak May 21 '13 at 09:49
4 Answers
Since you cannot create an instance of an abstract class you must use a derived class to test it. You can create a very simple class that extends the abstract class for testing purposes. When testing ensure that the subclass is used to test all methods requiring testing in the abstract class.

- 93,289
- 19
- 159
- 189
Here is how I would approach this...
- create a
protected
method in the test that returns an instance of theabstract
class calledgetInstance()
- implement this using the solutions suggested in the above links (test implementation of the class, mock or some default instance)
- call the
getInstance()
method from yoursetup
/@Before
method to populate a field that will be used for the tests
This approach will then allow you to reuse this set of tests when testing classes that extend your abstract class. You do this by having the test for the concrete class extend the test for the abstract class and override the getInstance
method to return an instance of the concrete class.

- 32,493
- 6
- 77
- 98
You could do as Kevin Bowersox says or you could use some mocking framework as well.
For example: Using Mockito to test abstract classes

- 1
- 1

- 8,615
- 10
- 58
- 81
Use an anonymous class with whatever implementation you want in the abstract methods.

- 412,405
- 93
- 575
- 722