使用JUnit和Powermock进行Emma代码覆盖

时间:2013-07-30 21:13:17

标签: junit powermock emma

我正在使用JUnit和Powermockito模拟。 我必须使用maven或ant进行CLI环境。

emma version:      ema-2.0.5312
powermock version: powermock-mockito-1.5.1-full
junit version:     junit-4.9

当我通过以下命令运行junit时,一切正常:

java org.junit.runner.JUnitCore some.package.ClassTest

然而,当我使用emma检查代码覆盖率时:

java emmarun -cp $CLASSPATH -report txt org.junit.runner.JUnitCore some.package.ClassTest

我收到以下错误:

1) initializationError(some.pakage.ClassTest)
   java.lang.ClassCastException: org.powermock.modules.junit4.PowerMockRunner cannot be cast to org.junit.runner.Runner

不使用powermock的其他测试类工作正常。 有没有人对此提出一些建议?提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用powermock时,您无法使用Emma找到覆盖范围

See this discussion on developer's side

答案 1 :(得分:0)

由于Eclemma与MockitoJUnitRunner一起使用,因此您可以使用MockitoJunitRunner并指定使用PowerMock的规则。

类似这样的东西:

@RunWith(MockitoJUnitRunner.class) // This supports Eclemma Plugin. Powermock doesn't.
@PrepareForTest({/* StaticClasses for Powermock here */})
public class ClassTest {

// These two statements; the static block and @Rule make sure Powermock works along with Mockito!!
static {
    PowerMockAgent.initializeIfNeeded();
}

@Rule
public PowerMockRule powerMockRule = new PowerMockRule();

@Mock // To mock dependent class
private MockClass mock;

@InjectMocks //To Inject all mocks in this class
private ClassUnderTest classObject;

//Rest of the code here.

}

需要依赖项:

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-rule-agent</artifactId>
        <version>1.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.10.19</version>
        <scope>test</scope>
    </dependency

此外,您还需要将其添加到Coverage As-> Coverage Configurations-> Arguments下的配置中。

内部VM参数添加-noverify并保存。enter image description here

要使其与Jacoco一起使用,请在pom.xml中使用以下语句。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
    <argLine>${argLine} -noverify -javaagent:${settings.localRepository}/org/powermock/powermock-module-javaagent/1.6.2/powermock-module-javaagent-1.6.2.jar</argLine>
    </configuration>
</plugin>