模拟 RestTemplate postforEntity
Mocking RestTemplate postforEntity
我有一个服务 class 看起来像 -
class A {
@Autowired
RestTemplate restTemplate;
public void method() {
res = restTemplate.postForEntity("http://abc", entity, Employee.class);
resBody = res.getBody();
}
}
以下是对其的测试Class-
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 成功运行
为什么 any() 在这里不起作用而 anyString() 起作用?我认为 any() 适用于任何数据类型。
看看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
中的 mock 似乎以 URI
作为第一个参数来覆盖该方法,因此您的 restTemplate.postForEntity("http://abc", entity, Employee.class)
不匹配。
如果您对当前模拟的方法感兴趣,只需输入一行,e。 G。 restTemplate.postForEntity(any(), any(), any())
然后只需将鼠标悬停在您最喜欢的方法上 IDE 即可在编译时查看已覆盖的确切(覆盖)方法。
我的问题很相似,将 null 转换为 String 对我有用:
when(restTemplateMock.postForEntity((String)isNull(), any(), eq(List.class)))
.thenReturn(responseEntityMock);
我有一个服务 class 看起来像 -
class A {
@Autowired
RestTemplate restTemplate;
public void method() {
res = restTemplate.postForEntity("http://abc", entity, Employee.class);
resBody = res.getBody();
}
}
以下是对其的测试Class-
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 成功运行
为什么 any() 在这里不起作用而 anyString() 起作用?我认为 any() 适用于任何数据类型。
看看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
中的 mock 似乎以 URI
作为第一个参数来覆盖该方法,因此您的 restTemplate.postForEntity("http://abc", entity, Employee.class)
不匹配。
如果您对当前模拟的方法感兴趣,只需输入一行,e。 G。 restTemplate.postForEntity(any(), any(), any())
然后只需将鼠标悬停在您最喜欢的方法上 IDE 即可在编译时查看已覆盖的确切(覆盖)方法。
我的问题很相似,将 null 转换为 String 对我有用:
when(restTemplateMock.postForEntity((String)isNull(), any(), eq(List.class)))
.thenReturn(responseEntityMock);