离线Jacoco使用MockStatic导致重新检测异常

时间:2016-02-03 07:10:08

标签: mockito powermock jacoco

我正在运行PowerMock 1.6.4和所有最新版本(JUnit 4.11)。

  • 我使用Jacoco Ant任务来只测试类,而不是测试类。我还使用Jacoco ant任务来运行Junit测试,然后生成报告。

现在我遇到了一个我无法弄清楚的问题......

  • 我有一个测试类,用于测试类Foo的一个成员函数。
  • Foo的一个成员是静态的,所以我把它包装在静态函数中,这样我就可以通过mock来控制执行,但副作用是我现在需要mockStatic。

我注意到的是 PowerMockito.mockStatic(Foo.class) ...所有测试都因仪器问题而失败。

我有另一个测试类来测试Foo的另一个成员函数。这个测试类工作正常,但是一旦我引入 mockStatic ,测试类就会因为检测失败而失败。

有没有人看到这种失败并知道任何变通方法?我无法更改静态成员变量。

2 个答案:

答案 0 :(得分:0)

我终于找到了我认为的问题。 Jacoco工具将数据注入到您的字节代码中,因此PowerMock在尝试模拟静态时也是如此。这会造成严重破坏,因为他们互相踩踏,你会因为互相混乱而得到奇怪的行为。我在代码中得到了各种各样的NPE,不应该抛弃NPE。

简单的解决方案是重构不必要的静态,并知道如果您打算使用静态控制数据流,如果您打算使用Jacoco进行覆盖,可能应该重新考虑测试架构。

你仍然可以在静力学上运行Jacoco仪器,但你不能同时模拟静力学;至少不是和Mockito的PowerMock一样。我不确定EasyMock是否会导致不同的行为,所以ymmv。

答案 1 :(得分:0)

I had similar issues, but instead of having to refactor the statics out I believe there is another solution. I did this in a maven pom file but I'll explain what is going on. Jacoco does inject data into your byte code. And yes Powermock uses a custom Byte loader and Jacoco hates that. So heres a solution to work around it.

In your Jacoco executions, you need Jacoco to use default-instrumentation for your tests. (you can specify powermock tests or just include all tests it works either way). Heres an explantion of whats going on with default-Instrumentation: Offline-instrumentation with Jacoco.

You must then have the restore step for the tests. Now heres the interesting part, you have to run the normal Jacoco Prepare Agent step, while EXCLUDING all the tests that were run in default instrumentation. (if you don't you will get a bunch of warnings something like JaCoCo exceution data already exists for xTest)

This will solve your problem, and you don't need to refactor out your static methods. Though if they were unnecessary you should probably still take them out ;)

UserObject.find_total_by_user_object_and_year(params)