I see no problem testing protected methods using JUnit. While the package structure for tests mirrors the structure of the source tree, methods other than private are visible for the tests.
Of course, if the implementation for testing is abstract, you must create the usual subclass of the class under the test yourself (or do it through some kind of mocking library, if it suits your purposes). Also in this case, there is no need to create a layer of public methods only for invoking protected visibility methods. For private methods only, this strategy does not work. But often you need to test private methods, one way or another, this is a sign of a design problem.
For example: The class for testing is in src / mypackage / AbstractClass.java package mypackage;
public class AbstractClass { protected int returnsOne() { return 1; } }
And the test which is in the tests /mypackage/AbstractClassTest.java
package mypackage; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class AbstractClassTest { @Test public void returnsOneReturnsOne() { AbstractClass instanceToTest = new AbstractClassTestable(); assertEquals(1, instanceToTest.returnsOne()); } } class AbstractClassTestable extends AbstractClass { }
source share