尝试创建一个模拟Mvc 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个选项,