【发布时间】:2021-11-13 18:23:30
【问题描述】:
当我在测试中调用端点时,我试图模拟一项服务,我正在使用带有黄瓜的 Spring Boot,我想模拟我的服务,但我总是得到真实的对象作为回报,但模拟工作正常当我直接从测试中调用服务时,我创建了一个示例来检查您是否可以提供帮助 这是我的测试课
package com.example.demo
import com.example.demo.service.DemoService
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.cucumber.spring.CucumberTestContext.SCOPE_CUCUMBER_GLUE
import io.restassured.RestAssured
import io.restassured.module.mockmvc.response.MockMvcResponse
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
import org.mockito.BDDMockito.given
import org.mockito.Mockito
import org.mockito.Mockito.mock
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.context.annotation.Scope
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.web.context.WebApplicationContext
import org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
@ContextConfiguration(classes = [DemoApplication::class])
@Scope(SCOPE_CUCUMBER_GLUE)
class Steps {
@LocalServerPort
var port: Int = 0
var demoService: DemoService = mock(DemoService::class.java)
@Autowired
private val webApplicationContext: WebApplicationContext? = null
@When("call the end point")
fun callTheEndPoint() {
val msg: Message = Message(id = "2", text = "test")
Mockito.`when`(demoService.getMessage()).thenReturn(msg)
RestAssured.port = port
RestAssured.baseURI = "http://localhost"
var res = RestAssured.`when`().get("/").then().extract().body().`as`(Message::class.java)
println("When is called: " + res.text)
}
@Then("retrieve these data")
fun retrieveData() {
println("Then is called")
}
}
这是我的 RestApi
package com.example.demo
import com.example.demo.service.DemoService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
data class Message(val id: String?, val text: String)
@RestController
class MessageResource {
@Autowired
lateinit var demoService: DemoService
@GetMapping
fun index(): Message = demoService.getMessage()
}
这是我的服务
package com.example.demo.service
import com.example.demo.Message
import org.springframework.stereotype.Service
@Service
class DemoService {
fun getMessage(): Message = Message(id = "1", text = "qwerty")
}
【问题讨论】:
标签: spring-boot kotlin cucumber