Spring Boot集成Cucumber测试调用接口时Mock服务不生效问题求助
问题根因
你在Steps类中手动创建的Mock对象没有注册到Spring IoC容器中,Controller层注入的是Spring默认初始化的真实DemoService实例,和你本地创建的Mock是完全独立的两个对象,因此接口调用不会触发Mock逻辑。
解决方案
使用Spring Boot提供的@MockBean注解替换手动Mock的代码,该注解会自动将容器中对应类型的原生Bean替换为Mockito Mock实例,同时将Mock实例注入到测试类中供你配置Stub逻辑。
修改后的测试类代码
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 org.mockito.Mockito import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.boot.web.server.LocalServerPort import org.springframework.context.annotation.Scope import org.springframework.test.context.ContextConfiguration @ContextConfiguration(classes = [DemoApplication::class]) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Scope(SCOPE_CUCUMBER_GLUE) class Steps { @LocalServerPort var port: Int = 0 // 替换手动Mock,使用@MockBean注入Spring容器托管的Mock实例 @MockBean private lateinit var demoService: DemoService @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") } }
验证说明
接口调用后返回的Message对象应为你预设的id="2"、text="test",你可以在Then步骤中添加断言验证结果正确性。
内容的提问来源于stack exchange,提问作者user1608962
相关产品推荐
相关产品推荐

