I really want to make 100% coverage including private methods in JUnit! (Basically, it is more natural to pass all through the public method test)
Suppose there is a private method in the following class that cannot pass the test naturally in only one place. (It's cute that the contents are squishy)
private String getStatus(String param, TestEntity testEntity) {
String result = null;
switch (param) {
case "1":
result = "A" + testEntity.getCode();
break;
case "2":
result = "B" + testEntity.getCode();
break;
case "3":
result = "C" + testEntity.getCode();
break;
default :
result = "Z" + testEntity.getCode (); // ← The coverage here does not pass!
}
return result;
}
Use Mockito https://site.mockito.org/
In my case, Spring Boot and JUnit have already been installed, so Add the following to dependency to get Mockito library.
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
dependencies {
// https://mvnrepository.com/artifact/org.mockito/mockito-all
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
}
Just write the following in the test class
private SampleUtil sampleUtil;
private static int testId = 1; // Variables used in later validation
@Test
public void getStatus() {
// Set to be able to execute SampleUtil # getStatus
Method method = SampleUtil.class.getDeclaredMethod("getStatus", String.class, TestEntity.class);
method.setAccessible(true);
// Parameter settings for testing
String param = "4";
TestEntity testEntity = new TestEntity();
testEntity.setCode("001");
// Test run
String status = (String) method.invoke(sampleUtil, param, testEntity);
assertThat(status, is("Z001"));
}
By setting accessible = true for getStatus () method of SampleUtil, it is possible to call it ignoring the accessor level.
The following testId is a variable defined private in SampleUtil.java. Let's get it here.
@Test
public void getParams() {
SampleUtil sampleUtil = new SampleUtil();
assertThat(Whitebox.getInternalState(sampleUtil, "testId"), is(1));
}
By implementing in this way, it is possible to call while ignoring the accessor level.
In addition to the functions introduced here, it has many functions such as rewriting static methods and expanding the range of JUnit tests. If you are interested, you may want to dig in and check it out.
Recommended Posts