2017-03-15 55 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"; 
    }