Spring Boot-MockMvc GET(黄瓜)的结果为空

问题描述 投票:0回答:1

尝试创建一个模拟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,不走运。

我要去哪里错了?我有正确的注释吗?

java spring cucumber mockmvc
1个回答
0
投票

通过模拟您的bean,您将获得所有结果为null。

您有2个选项,

  1. 您继续嘲笑,但是您使用when / then定义行为
  2. 您监视自己的bean:然后它将像正常情况一样“执行”操作,您可以仅存入不需要的方法。
© www.soinside.com 2019 - 2024. All rights reserved.