【发布时间】:2020-12-05 20:01:39
【问题描述】:
我有一个方法,我想创建一些单元测试(这个方法变形
applicationContext.getEnvironment().getProperty(key, class)
用于领事集成)
长话短说:
public class DynamicProperties {
public <T> T getEnvironmentProperty(String key, Class<T> cls) {
return cls.cast(applicationContext.getEnvironment().getProperty(key,cls));
}
}
在测试其他使用 DynamicProperties 类的类时,如下:
@Test
void testA() {
//before
when(dynamicProperties.getEnvironmentProperty(eq(KEY_A), Boolean.class)).thenReturn(true);
when(dynamicProperties.getEnvironmentProperty(eq(KEY_B), Long.class)).thenReturn(0l);
//when
archivedSensorsService.testMethod();
//than
verify(...)
}
KEY_A KEY_B 是公共静态最终字符串 我收到以下错误:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
尝试以下操作时:
@Test
void testA() {
//before
when(dynamicProperties.getEnvironmentProperty(eq(KEY_A), anyObject())).thenReturn(true);
when(dynamicProperties.getEnvironmentProperty(eq(KEY_B), anyObject())).thenReturn(0l);
//when
archivedSensorsService.testMethod();
//than
verify(...)
}
得到以下错误:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'getEnvironmentProperty' method:
dynamicProperties.getEnvironmentProperty(
null,
null
);
-> at com.xxx.xxx ionNotBeenTriggered(..)
- has following stubbing(s) with different arguments:
1. dynamicProperties.getEnvironmentProperty(
null,
null
);
有什么建议吗?
【问题讨论】:
标签: java unit-testing mocking spring-boot-test