How to test abstract class in Java with JUnit? How to test abstract class in Java with JUnit? java java

How to test abstract class in Java with JUnit?


If you have no concrete implementations of the class and the methods aren't static whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.

I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected and public, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.


Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.


With the example class you posted it doesn't seem to make much sense to test getFuel() and getSpeed() since they can only return 0 (there are no setters).

However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.

For example, in your TestCase you could do this:

c = new Car() {       void drive() { };   };

Then test the rest of the methods, e.g.:

public class CarTest extends TestCase{    private Car c;    public void setUp()    {        c = new Car() {            void drive() { };        };    }    public void testGetFuel()     {        assertEquals(c.getFuel(), 0);    }    [...]}

(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)