During unit testing, the method I wanted to test called a protected method, but the protected method was difficult to decipher (ancient heritage) and the implementation of test cases was difficult.
So I came up with the idea of overriding the protected method with an anonymous class and stubbing it.
JUnit used 4.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Target.java
public class Target {
//The method you want to test
public int wantTesting(int x) {
return getNum(x);
}
//Protected method called by the method you want to test
protected int getNum(int x) {
return x + 100;
}
}
TargetTest.java
import org.junit.Assert;
import org.junit.Test;
public class TargetTest {
@Test
public void testWantTesting() {
Target target = new Target();
Assert.assertEquals(101, target.wantTesting(1));
Target target2 = new Target() {
@Override
protected int getNum(int x) {
return 9999;
}
};
Assert.assertEquals(9999, target2.wantTesting(1));
}
}
Recommended Posts