Component
public class MyService {
private final ObjectMapper objectMapper = new ObjectMapper();
private final RestTemplate restTemplate = new RestTemplate();
public void myMethod(){
------- codes to test above it------
HttpEntity<String> httpEntity = new HttpEntity<>(objectMapper
.writeValueAsString(message), httpHeaders);
String response = restTemplate
.postForObject(getUrl(), httpEntity, String.class);
}
}
我试过@Spy,但它不起作用
@InjectMocks
private MyService myService;
@Spy
private RestTemplate restTemplate;
when(restTemplate.postForObject(
getUrl(),
httpEntity,
String.class
)).thenReturn(getResponse());
如果你想侦察:
@Test
void test(){
MyService myService = Mockito.spy(MyService.class);
myService.myMethod();
}
通过这种方式,您可以获得RestTemplate的实例。
我个人更喜欢将RestTemplate作为依赖项接收,这样可以很容易地进行模拟。
例如:
private final RestTemplate restTemplate;
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
在你的测试
//@RunWith(MockitoJUnitRunner.class) //junit4
@ExtendWith(MockitoExtension.class) //junit 5
public class MyServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private MyService myService;
@Test
void test(){
when(restTemplate.postForObject(
getUrl(),
httpEntity,
String.class
)).thenReturn(getResponse());
//do whatever you like
}
}
spring引导测试通过MockBean和SpyBean注释提供了一种很好的方法来模拟bean。
尝试使用@SpyBean
代替@Spy
,使用@MockBean
代替@Mock
。
@MockBean
private RestTemplate restTemplate
在这种情况下,不需要@InjectMocks
。