簡體   English   中英

Spring Boot - MockMvc 結果為 GET(黃瓜)

[英]Spring Boot - MockMvc result null for GET (Cucumber)

我在嘗試創建 mockMvc get請求時遇到問題,在請求獲取 JSON 對象時收到空結果。 我知道我可以創建一個很好的post ,但是在我的控制器中調用 GET 端點時很難接收數據。

AddressStepDefs.java

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= WebEnvironment.MOCK)
@Transactional
@AutoConfigureMockMvc
/**
 * Address Step Definition class to execute Scenario(s) contained in Address.feature
 * @author Lewis Jones
 *
 */
public class AddressStepDefs {

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private MockMvc mockMvc;

    private ResultActions result;

    @Autowired
    @MockBean
    private AddressRepository addressRepo;

    /**
     * Build the Controller under test
     */
    @BeforeClass
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new AddressController()).build(); 
    }

    /**
     * Set the mock server up
     */
    @Before
    public void serverSetup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    /**
     * Build the WebApplicationContext
     */
    @Given("The server is up and running")
    public void the_server_is_up_and_running() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @When("I request to view an Address with id {int} at {string}")
    public void i_request_to_view_an_Address_with_id_at(Integer id, String request) throws Exception {
        /** Build a GET request using mockMvc **/
        result = this.mockMvc.perform(get(request + id).contentType(MediaType.APPLICATION_JSON));
    }

    @Then("the response code should be OK {int} and the resulting Address object json should be:")
    public void the_response_code_should_be_OK_and_the_resulting_Address_object_json_should_be(Integer responseCode, String json) throws Exception {
        result.andExpect(status().is(responseCode));
        result.andExpect(content().string(json));
    }
  • 控制器端點和請求很好。
  • 數據庫中有數據。
  • 它在沒有@MockBean ,但是我的post實際上將數據插入到數據庫中。 (這不是我想要的)
  • 我試過@InjectMocks ,沒有運氣。

我哪里錯了? 我有正確的注釋嗎?

通過模擬您的 bean,您將獲得所有結果為 null。

你有2個選擇,

  1. 您繼續模擬,但您使用 when/then 定義行為
  2. 你監視你的 bean:然后它會像往常一樣“做同樣的事情”,你可以存根你不想要的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM