我有个服务舱,看上去-
class A {
@Autowired
RestTemplate restTemplate;
public void method() {
res = restTemplate.postForEntity("http://abc", entity, Employee.class);
resBody = res.getBody();
}
}以下是它的测试课程-
class TestA {
@Mock
RestTemplate restTemplate;
@InjectMocks
A obj;
void testMethod1() {
res = ....
when(restTemplate.postForEntity(any(), any(), any()).thenReturn(res);
}
void testMethod2() {
res = ....
when(restTemplate.postForEntity(anyString(), any(), any()).thenReturn(res);
}
}testMethod1在"res.getBody() from A.method()“上抛出NullPointerException失败,而testMethod2成功运行
为什么在anyString()工作时没有()在这里工作?我认为任何()都适用于任何数据类型。
发布于 2021-02-02 18:36:39
看看Javadocs for RestTemplate。有三种postForEntity方法:
postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)postForEntity(URI url, Object request, Class<T> responseType)testMethod2中的模拟可以肯定地捕捉到这两种方法中的一种。但是,您的testMethod1中的模拟似乎用URI作为第一个参数来覆盖该方法,因此您的restTemplate.postForEntity("http://abc", entity, Employee.class)不匹配。
如果您对当前模拟的方法感兴趣,只需键入一行,例如restTemplate.postForEntity(any(), any(), any()),然后在您喜爱的IDE中的方法上悬停以查看编译时已经覆盖的确切(重写)方法。
发布于 2022-02-27 10:55:09
我的问题与此相似,将空转换为对我有用的字符串:when(restTemplateMock.postForEntity((String)isNull(), any(), eq(List.class))) .thenReturn(responseEntityMock);。
https://stackoverflow.com/questions/66010969
复制相似问题