[英]Autowired MockMvc is null with JUnit 5 and Spring boot
[英]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個選擇,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.