How to test protected methods of an abstract class using JUnit and JMock

I have this situation - I have an interface (say MyInterface ) and a simple partial implementation ( AbstractMyInterface ). The latter adds some protected methods that I would like to test.

Currently, I am just writing manually a layout that extends AbstractMyInterface and exports protected methods as public. Is there an easier way to do this - for example, using JMock + scripts?

+4
source share
3 answers

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;

 /** This could as well implement some interface, but that does not change a thing */ 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()); } } /** This is needed, because we cannot construct abstract class directly */ class AbstractClassTestable extends AbstractClass { } 
+6
source

Just an offer

What if we do not test protected methods, can we use public methods to protect these protected methods?

If not, it is because of too complicated protected methods, refactoring to extract complex things to a new object that provides public interfaces, leaving the old object with only one private object in some public methods.

The test will be later at the new facility.

This blog comment may be helpful.

+3
source

you can make an abstract test case for an interface (or an abstract class). then create a specific test case that extends your abstract test case for each specific implementation of your interface (or abstract class).

0
source

Source: https://habr.com/ru/post/1384574/


All Articles