零星行为 未捕获任何参数值!使用 PowerMockito SpringBoot 实现静态 NewRelic 的 ArgumentCaptor

ken*_*ken 5 unit-testing powermock newrelic spring-boot powermockito

将 NewRelic 自定义参数添加到日志记录库的关键部分。嘿,我应该添加正确的测试来验证调用是否正确。为 NewRelic() 编写了几个测试来验证和 ArgumentCaptor,有时它们可​​以工作。有时,他们不这样做。使用intellij、gradle、SpringBoot(1.4.2)。

compile group: 'com.newrelic.agent.java', name: 'newrelic-api', version: '3.26.1'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.6.5'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.6.5'
Run Code Online (Sandbox Code Playgroud)

问题:

随机PowerMockito.mockStatic(NewRelic.class);无法捕获参数。

代码

测试使用以下代码片段:

@RunWith(PowerMockRunner.class)
@PrepareForTest({NewRelic.class})
public class NewRelicAddCustomParameterWrapperTest {
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(NewRelic.class);
PowerMockito.spy(NewRelic.class);
} 
@Test
public void addCustomParam() throws Exception {
//GIVEN
String key = "woopsie-doo1";
String value = "tippyConue";
PowerMockito.spy(NewRelic.class);
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(NewRelic.class, "addCustomParameter", captor.capture(), captor2.capture());
//WHEN
newRelicAddCustomParameterWrapper.addCustomParam(key, value);
//THEN
String resourceKey = captor.getValue();
Run Code Online (Sandbox Code Playgroud)

'NewRelicAddCustomParameterWrapper` 类是包装 NewRelic 调用的简单方法:

public void addCustomParam(final String key, final String value) {
// Create a component to wrapper the static NewRelic
try {
NewRelic.addCustomParameter(key, value);
} catch (Exception newRCustomException) {
newRCustomException.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)

会发生什么症状行为:

  1. 当运行单个测试时,大多数情况下它都有效
  2. 如果运行所有 5 个测试组,PowerMockito 会失败(仅 Mockito 测试通过)
  3. 当运行调试模式时,在任何地方放置一个停止点,ALL PASS 一致
  4. 当运行调试模式时,没有中断,像运行模式一样随机失败。

- 错误

No argument value was captured!在这行代码上: String resourceKey = captor.getValue();

来自控制台的错误片段:

您可能忘记在 verify() 中使用 argument.capture() ... ...或者您在存根中使用 capture() 但未调用存根方法。请注意,建议仅将 capture() 与 verify() 一起使用

正确的参数捕获示例: ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); 验证(模拟).doSomething(argument.capture()); assertEquals("John", argument.getValue().getName());

org.mockito.exceptions.base.MockitoException:未捕获任何参数值!您可能忘记在 verify() 中使用 argument.capture() ... ...或者您在存根中使用 capture() 但未调用存根方法。请注意,建议仅将 capture() 与 verify() 一起使用

——想法和问题:

  • 尝试到处添加Thread.sleep(900)都无济于事。哈哈 :)
  • 调试没有帮助,因为它有效。
  • Is there a conflict between PowerMockito & Mockito?
  • Is PowerMock better PowerMockito: which should I be using?
  • 调试跳转到 .when 方法应该被拦截,MockGateway执行类似于模拟方法的操作。
  • clean在项目上重新运行 gradle
  • PowerMockito 和 Mockito 之间的类加载是否冲突?怎么算?

我在这上面花了太多时间。这是一段重要的代码,需要良好的测试覆盖率。任何关于如何进行的想法、想法、建议将不胜感激。

github 上的简单示例项目: 代码链接:NewRelic PowerMockito 静态单元测试 NewRelic.addCustomParameter(key, value);