0

我已经在@Configuration课堂上配置了必要的 Bean,但无法将 RestTemplate 注入我的测试类进行测试。

@Configuration
public class AppConfig {
    @Bean
    public ProtobufHttpMessageConverter protobufHttpMessageConverter() {
        return new ProtobufHttpMessageConverter();
    }
    @Bean
    public RestTemplate restTemplate(ProtobufHttpMessageConverter converter) {
        RestTemplate http2Template = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        List<HttpMessageConverter<?>> converters = http2Template.getMessageConverters();
        converters.add(converter);
        http2Template.setMessageConverters(converters);
        return http2Template;
    }
}

测试类:

@ExtendWith(SpringExtension.class)
@AutoConfigureWebClient(registerRestTemplate = true)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {RestTemplate.class, ProtobufHttpMessageConverter.class})
@ActiveProfiles("dev")
public class GRPCRestApiTest {
    @Autowired
    private RestTemplate restTemplate;
    @Test
    public void GetOneCourseUsingRestTemplate() throws IOException {
        assertNotNull(restTemplate, "autowired restTemplate is NULL!");
        ResponseEntity<Course> course = restTemplate.getForEntity(COURSE_URL, Course.class);
        assertResponse(course.toString());
        HttpHeaders headers = course.getHeaders();
    }
}

任何建议和见解表示赞赏

4

1 回答 1

0

classes注释的属性@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {RestTemplate.class, ProtobufHttpMessageConverter.class})采用组件类来加载应用程序上下文。除了主 Spring Boot 类之外,您不应该在此处输入任何内容或将其留空。

此外@AutoConfigureWebClient(registerRestTemplate = true),当您想使用您在应用程序中配置的 bean 时(至少这是我从您的问题中理解的)。

因此,您的测试设置应如下所示:

// @ExtendWith(SpringExtension.class) can be omitted as it is already part of @SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("dev")
public class GRPCRestApiTest {

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void GetOneCourseUsingRestTemplate() throws IOException {
        assertNotNull(restTemplate, "autowired restTemplate is NULL!");
        ResponseEntity<Course> course = restTemplate.getForEntity(COURSE_URL, Course.class);
        assertResponse(course.toString());
        HttpHeaders headers = course.getHeaders();
    }
}

这现在应该在配置文件中启动您的整个 Spring Boot 上下文,dev并且您应该可以访问您在生产代码中定义的所有 bean,例如AppConfig.

于 2020-06-14T20:18:07.907 回答