RestTemplate抛出NoHttpResponseException

时间:2018-07-18 23:53:08

标签: spring junit kotlin resttemplate mockmvc

最初我是下面的代码,一切都很好。

@Service
class MyService(
    private val restTemplateBuilder: RestTemplateBuilder
) {

fun getSavedInfo(number: String): SavedResponse {
        return restTemplateBuilder.getRestTemplate()
                .postForObject(
                        "$hostname/saved-info",
                        InfoRequest(number),
                        InfoResponse::class.java
                )
}

但是当我更改为此

@Service
class MyService(
    private val restTemplate: RestTemplate
) {

fun getSavedInfo(number: String): SavedResponse {
        return restTemplate
                .postForObject(
                        "$hostname/saved-info",
                        InfoRequest(number),
                        InfoResponse::class.java
                )
}

随机测试用例开始失败,并显示NoHttpResponseException

const val MP_PORT = 8988

@RunWith(SpringRunner::class)
@AutoConfigureMockMvc
@SpringBootTest(properties = [
    "mp.hostname=http://localhost:$MP_PORT"
])
class MPControllerTest {

    @Autowired
    lateinit var mockMvc: MockMvc

    @Rule
    @JvmField
    final val wireMockRule = WireMockRule(MP_PORT)

    val mapper = ObjectMapper()

    @Test
    fun testSavedInfo() {
        val mpResponse = """
            {
                "status": "200",
                "code": "200",
                "message": "ok",
                "time": "now",
                "correlationId": "1234",
                "data":{
                    "responseCode": 0,
                    "errorDescription": "",
                    "newBalance": 1234,
                    "newExpiryDate": "12/06/2016",
                    "receiptNo": "45678"
                }
            }

        """
        val savedRequest = SavedRequest("0555", 1234, 50)

        val request = mapper.writeValueAsString(savedRequest)

        stubFor(post(urlEqualTo("/savedInfoBackend"))
                .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(mpResponse)))

        mockMvc
            .perform(MockMvcRequestBuilders
                .post("/api/payment/savedInfo")
                .contentType(MediaType.APPLICATION_JSON)
                .content(request)
            )
            .andExpect(MockMvcResultMatchers.status().isOk)
            .andExpect(MockMvcResultMatchers.jsonPath("$.receiptNo", `is`("45678")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.newExpiryDate", `is`("12/06/2016")))
            .andReturn()
    }

RestTemplate来自于配置类@Bean

我想重新使用RestTemplate。不知道这里出了什么问题。任何帮助表示赞赏。

0 个答案:

没有答案