在Spring集成测试中模拟RestTemplateBuilder和RestTemplate

use*_*892 7 java spring mockito resttemplate

我有一个REST资源,它被RestTemplateBuilder注入以构建一个RestTemplate:

public MyClass(final RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = restTemplateBuilder.build();
}
Run Code Online (Sandbox Code Playgroud)

我想测试那个课程.我需要模拟RestTemplate对其他服务的调用:

request = restTemplate.getForEntity(uri, String.class);
Run Code Online (Sandbox Code Playgroud)

我在我的IT中试过这个:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIT {

@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private RestTemplateBuilder restTemplateBuilder;
@Mock
private RestTemplate restTemplate;

@Test
public void shouldntFail() throws IOException {

    ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    when(restTemplateBuilder.build()).thenReturn(restTemplate);
    when(restTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
...
ResponseEntity<String> response = testRestTemplate.postForEntity("/endpoint", request, String.class);
  ...
}
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我得到以下异常:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.test.web.client.TestRestTemplate': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: RestTemplate must not be null
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

And*_*own 8

你的问题是执行的顺序.创建上下文包含您MockBean之前有机会在您的内容中设置它@Test.解决方案是在RestTemplateBuilder插入上下文时提供已完全设置的解决方案.你可以这样做.

将以下内容添加到@SpringBootTest注释中.TestApplication你的Spring Boot应用程序类在哪里.

classes = {TestApplication.class, MyIT.ContextConfiguration.class},
Run Code Online (Sandbox Code Playgroud)

因此,修改您的类成员,删除您的restTemplate和restTemplateBuilder.

@Autowired
private TestRestTemplate testRestTemplate;
Run Code Online (Sandbox Code Playgroud)

在类中添加静态内部MyIT类:

@Configuration
static class ContextConfiguration {
  @Bean
  public RestTemplateBuilder restTemplateBuilder() {

    RestTemplateBuilder rtb = mock(RestTemplateBuilder.class);
    RestTemplate restTemplate = mock(RestTemplate.class);

    when(rtb.build()).thenReturn(restTemplate);
    return rtb;
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的测试中,修改RestTemplate模拟以执行您想要的任何操作:

@Test
public void someTest() {

  when(testRestTemplate.getRestTemplate().getForEntity(...
}
Run Code Online (Sandbox Code Playgroud)