我尝试在Cucumber测试中使用MockMvc,但没有解决Spring依赖关系。
我创建了这个课程:
@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty", features = "src/test/resources/features"})
@SpringBootTest
public class CucumberTest {
}
运行黄瓜功能
这个课程的步骤:
@WebMvcTest(VersionController.class)
@AutoConfigureWebMvc
public class VersionControllerSteps {
@Autowired
private MockMvc mvc;
private MvcResult result;
@When("^the client calls /version$")
public void the_client_issues_GET_version() throws Throwable {
result = mvc.perform(get("/version")).andDo(print()).andReturn();
}
@Then("^the client receives status code of (\\d+)$")
public void the_client_receives_status_code_of(int statusCode) throws Throwable {
assertThat(result.getResponse().getStatus()).isEqualTo(statusCode);
}
@And("^the client receives server version (.+)$")
public void the_client_receives_server_version_body(String version) throws Throwable {
assertThat(result.getResponse().getContentAsString()).isEqualTo(version);
}
}
但是抛出异常:
java.lang.NullPointerException
at com.example.rest.VersionControllerSteps.the_client_issues_GET_version(VersionControllerSteps.java:30)
at ✽.When the client calls /version(version.feature:8)
这是.feature:
Feature: the version can be retrieved
As a api user
I want to know which api version is exposed
In order to be a good api user
Scenario: client makes call to GET /version
When the client calls /version
Then the client receives status code of 200
And the client receives server version 1.0
如何配置我的测试以使用黄瓜和弹簧启动?
提前致谢。
答案 0 :(得分:1)
添加@ContextConfiguration(classes = .class)如下所示
@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty", features = "src/test/resources/features"})
@SpringBootTest
@ContextConfiguration(classes = <SpringBootApplication>.class)
public class CucumberTest {
}
这会奏效。我遇到了同样的问题,并通过这个解决方案得到了解决。
答案 1 :(得分:0)
从您的代码清单和错误日志中,不清楚黄瓜+弹簧设置是否存在问题或仅是应用程序错误。
堆栈跟踪指向第30行,这是抛出空指针异常。从您的代码列表看,它可能是由于result.getResponse().getContentAsString()
说明。
如果您的控制器实际上正在返回身体,则可能值得检查。例如,您可能需要使用@ResponseBody
注释
@RequestMapping(
value = "/campaigns/new",
method = RequestMethod.GET,
)
public @ResponseBody String vers() {
return "1.0.1";
}