首页 > 解决方案 > 零星行为 未捕获任何参数值!使用 PowerMockito SpringBoot 的静态 NewRelic 的 ArgumentCaptor

问题描述

将 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'

问题:

随机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();

'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();
}
}

会发生什么症状行为:

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

- 错误

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

来自控制台的错误片段:

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

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

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

-- 想法和问题:

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

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

标签: unit-testingspring-bootpowermocknewrelicpowermockito

解决方案


推荐阅读