如何在Java Spring中模拟RestTemplate?
2022-09-02 00:53:37
public class ServiceTest {
@Mock
RestTemplate restTemplate = new RestTemplate();
@InjectMocks
Service service = new Service();
ResponseEntity responseEntity = mock(ResponseEntity.class);
@Test
public void test() throws Exception {
Mockito.when(restTemplate.getForEntity(
Mockito.anyString(),
Matchers.any(Class.class)
))
.thenReturn(responseEntity);
boolean res = service.isEnabled("something");
Assert.assertEquals(res, false);
}
我试图为包括休息客户端在内的服务测试一个简单的测试。看起来我没有成功嘲笑。看起来代码获取的是真实数据,而不是模拟数据。任何人都可以帮助我。RestTemplate
服务本身将如下所示:
public class Service{
public boolean isEnabled(String xxx) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity("someurl",String.class);
if(...)return true;
return false;
}
}