![](/img/trans.png)
[英]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.