【问题标题】:TestRestTemplate with Spring-boot and Integration Testins带有 Spring-boot 和集成测试的 TestRestTemplate
【发布时间】:2026-01-16 21:05:01
【问题描述】:

我正在为我的 spring-boot 项目运行一套集成测试。当我尝试在 REST 端点上运行测试时,出现以下异常:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.edelweissco.ofac.model.About] and content type [text/html;charset=UTF-8]

"localhost" == entity.getLocation().toString()
            |  |      |             |
            |  |      null          null
            |  [Server:[Apache-Coyote/1.1], X-Content-Type-Options:[nosniff], X-XSS-Protection:[1; mode=block], Cache-Control:[no-cache, no-store, max-age=0, must-revalidate], Pragma:[no-cache], Expires:[0], X-Frame-Options:[DENY], Set-Cookie:[JSESSIONID=DA7CDC16560B2183844B6ADDFC23944E; Path=/; HttpOnly], Content-Type:[text/html;charset=UTF-8], Content-Length:[550], Date:[Sun, 22 Jun 2014 03:05:11 GMT]]
            false
            8 differences (11% similarity)
            (loca)l(host)
            (nul-)l(----)

这是我正在测试的课程:

@Controller
public class AboutController {

private static final String ABOUT = "about";

private static final Logger LOG = LoggerFactory.getLogger( AboutController.class );

@Autowired
private ConfigurationSettings configuration;

@RequestMapping(value = "/about", method = RequestMethod.GET)
public String get(Model model) {

    LOG.debug( "AboutController to about view" );
    About about = new About( configuration.getAboutVersion(), configuration.getAboutCopyright(), configuration.getAboutProduct() );
    model.addAttribute( ABOUT, about );
    return "/" + ABOUT;
}

}

这是我的测试:

@ContextConfiguration(classes = OFAC, loader = SpringApplicationContextLoader)
@Transactional
class AboutControllerTest extends BaseSpecification {

    @Autowired
    private ConfigurationSettings configurationSettings;

    RestTemplate template = new TestRestTemplate();

    @Autowired
    private AboutController aboutController;



    def "test the actual endpoint"() {
        def url = "http://localhost:" + configurationSettings.getServerPort() + "/about"

        HttpHeaders headers = new HttpHeaders();

        when:
        def entity = new TestRestTemplate("user", "password").exchange(
                url, HttpMethod.GET, new HttpEntity<Void>(
                headers), About.class);

        then:
        entity.getStatusCode() == HttpStatus.FOUND;
    }


    def "testing url"() {
        def url = "http://localhost:" + configurationSettings.getServerPort() + "/about"

        when:
        def entity  = template.getForEntity(url, String.class).getHeaders()

        then:
        "localhost" == entity.getLocation().toString()
    }
}

我的 MVC 有以下配置:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController( "/home" ).setViewName( "index" );
        registry.addViewController( "/" ).setViewName( "index" );
        registry.addViewController( "/about" ).setViewName( "about" );
        registry.addViewController( "/login" ).setViewName( "login" );
        registry.addViewController( "/upload" ).setViewName( "upload" );
        registry.addViewController( "/status" ).setViewName( "status" );
        registry.addViewController( "/search" ).setViewName( "search" );
        registry.addViewController( "/admin" ).setViewName( "admin" );
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName( "lang" );
        registry.addInterceptor( localeChangeInterceptor );
    }

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
        cookieLocaleResolver.setDefaultLocale( StringUtils.parseLocaleString( "en" ) );
        return cookieLocaleResolver;
    }

    @Bean
    public MessageSource messageSource() {

        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames( "classpath:messages/messages", "classpath:messages/validation" );
        // if true, the key of the message will be displayed if the key is not
        // found, instead of throwing a NoSuchMessageException
        messageSource.setUseCodeAsDefaultMessage( true );
        messageSource.setDefaultEncoding( "UTF-8" );
        // # -1 : never reload, 0 always reload
        messageSource.setCacheSeconds( 0 );
        return messageSource;
    }
}

我没有配置任何 HttpMessageConverter,因为我的项目只是在 REST 调用中使用 Thymeleaf 和模型。我寻找将 TestRestTemplate 与集成测试一起使用的示例,但并没有真正看到与我正在尝试做的事情类似的任何事情。

我将不胜感激有关此测试的任何提示,或进行全栈集成测试的更好方法。

【问题讨论】:

    标签: spring-boot thymeleaf spring-test


    【解决方案1】: