2

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?

Shan
  • 5,054
  • 12
  • 44
  • 58
  • 1
    Do you want to create test cases for non abstract methods of abstract calss? – Despicable May 21 '13 at 09:46
  • 1
    see 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 Answers4

4

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Here is how I would approach this...

  • create a protected method in the test that returns an instance of the abstract class called getInstance()
  • 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 your setup / @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.

John B
  • 32,493
  • 6
  • 77
  • 98
0

You could do as Kevin Bowersox says or you could use some mocking framework as well.

For example: Using Mockito to test abstract classes

Community
  • 1
  • 1
Laimoncijus
  • 8,615
  • 10
  • 58
  • 81
0

Use an anonymous class with whatever implementation you want in the abstract methods.

Bohemian
  • 412,405
  • 93
  • 575
  • 722