【问题标题】:Spring boot v2 No qualifying bean of type TestRestTemplateSpring boot v2 没有 TestRestTemplate 类型的限定 bean
【发布时间】:2021-12-28 07:34:19
【问题描述】:

我在尝试获取 TestRestTemplate 时遇到错误。有什么方法可以获取 TestRestTemplate 或者测试 ErrorController?

错误日志:https://pastebin.com/XVPU9qrb

Main test class:

package io.kuark.ppalli

import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT
import org.springframework.test.context.ActiveProfiles

@ActiveProfiles("test")
@SpringBootTest(classes = [PpalliApi::class], webEnvironment = RANDOM_PORT)
class PpalliApiTest {

  @Test
  fun contextLoads() {}
}

Unit test class:


import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.web.client.TestRestTemplate
import kotlin.test.assertEquals

@WebMvcTest
class FallbackErrorControllerTest {

  @Autowired
  lateinit var http: TestRestTemplate

  @Test
  fun handleError() {
    val result = http.getForObject("/error", String::class.java);

    assertEquals("""{"code": "NOT_FOUND"}""", result)
  }
}

【问题讨论】:

    标签: spring spring-boot kotlin spring-boot-test spring-mvc-test


    【解决方案1】:

    使用@WebMvcTest 时,Spring Boot 不会启动嵌入式 Tomcat 服务器,您将无法通过端口访问端点。相反,Spring Boot configures a mocked servlet environment that you directly interact with using MockMvc:

    @WebMvcTest
    class FallbackErrorControllerTest {
    
      @Autowired
      lateinit var mockMvc: MockMvc
    
      @Test
      fun handleError() {
        mockMvc.perform(get("/error")).andExpect(status().isOk);
      }
    }
    

    MockMvc 甚至带有自己的Kotlin DSL

    但是,当使用 @SpringBootTestwebEnvironment=RANDOM_PORT 时,Spring Boot 会自动配置 Tomcat 并在随机端口上公开您的应用程序。这将是一个真正的 servlet 环境,您可以在其中使用 TestRestTemplate 作为 HTTP 客户端来交互和测试您的端点。

    【讨论】:

      猜你喜欢
      • 2016-07-04
      • 1970-01-01
      • 2020-01-10
      • 2015-03-27
      • 2016-11-17
      • 2016-11-30
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      相关资源
      最近更新 更多