当我使用@PrepareForTest提示时,即使测试用例,雅各布也显示0%的覆盖率。
下面是我的示例代码。我想测试WebOmnibarLookupServiceImpl类公共方法loadWebOmnibarLookupCache()。在其调用私有方法getWebOmnibarDictionaryKey中。
@RunWith(PowerMockRunner.class)
@PrepareForTest({QueryRequestUpdater.class, WebOmnibarLookupServiceImpl.class})
public class WebOmnibarLookupServiceImplTest {
@InjectMocks
private WebOmnibarLookupServiceImpl service = new WebOmnibarLookupServiceImpl();
@Test
public void testloadWebOmnibarLookupCache() throws Exception {
WebOmnibarLookupServiceImpl privateService = PowerMock.createPartialMock(WebOmnibarLookupServiceImpl.class, "getWebOmnibarDictionaryKey");
PowerMock.expectPrivate(privateService, "getWebOmnibarDictionaryKey", TestData.getSearchQueryRequestDTOForCache()).andReturn(TestData.getWebOmnibarDictionaryKey());
doReturn(TestData.getSearchResponseObj()).when(webOmnibarDictionaryCache).get(any());
service.loadWebOmnibarLookupCache(TestData.getSearchQueryRequestDTOForCache());
}
}
Maven配置:
<profiles>
<profile>
<id>sonar-coverage</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<append>true</append>
<excludes>
<exclude>**/*Config.*</exclude>
<exclude>**/*Constants.*</exclude>
<exclude>**/*Enum.*</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>agent-for-ut</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-instrument</id>
<goals>
<goal>instrument</goal>
</goals>
</execution>
<execution>
<id>default-restore-instrumented-classes</id>
<goals>
<goal>restore-instrumented-classes</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/coverage.exec</dataFile>
</configuration>
</execution>
<execution>
<id>agent-for-it</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
在这里,我使用@@ PrepareForTest({WebOmnibarLookupServiceImpl.class})模拟私有方法。 在这里,测试成功执行,但是该类的覆盖率显示为0%,只有那些类没有添加,@ PrepareForTest显示覆盖率。 在执行测试用例时,我正在警告消息下方。
[WARNING] Classes in bundle 'webanalytics-server' do no match with execution data. For report generation the same class files must be used as at runtime.
[WARNING] Execution data for class com/shn/webanalytics/service/impl/WebOmnibarLookupServiceImpl does not match.