2017-03-15 60 views
5

我尝试在Cucumber测试中使用MockMvc,但没有解决弹簧依赖问题。@RunWith(Cucumber.class)和@Autowired MockMvc

我已经创建这个类:

@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) 

这是.fe ature:

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

哪个精确指令引发空指针异常? – Antonio

回答

0

从你的代码清单和错误日志中,不清楚它是一个黄瓜+弹簧设置的问题还是只是一个应用程序错误。

堆栈跟踪指向第30行,它引发空指针异常。从您的代码清单看,它可能是由于result.getResponse().getContentAsString()说明。

这可能是值得检查你的控制器是否实际返回一个正文。例如,您可能需要使用@ResponseBody注释标记返回的值

@RequestMapping(
    value = "/campaigns/new", 
    method = RequestMethod.GET, 
    ) 
    public @ResponseBody String vers() { 
     return "1.0.1"; 
    }