繁体   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