3

我正在使用 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 的测试类工作正常。有人对此有什么建议吗?提前致谢。

4

2 回答 2

1

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

请参阅开发人员方面的此讨论

于 2013-11-19T07:10:34.360 回答
0

You can use MockitoJunitRunner and specify a rule to use PowerMock since Eclemma works along with MockitoJUnitRunner.

Something like this:

@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.

}

Dependencies needed:

    <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

Also you need to add this to the configurations under Coverage As -> Coverage Configurations -> Arguments.

Inside VM Arguments add -noverify and save.enter image description here

for this to work with Jacoco use the following statement in your 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>
于 2018-09-04T09:13:48.737 回答