简体   繁体   中英

Spring Boot - MockMvc result null for GET (Cucumber)

I am running into an issue when trying to create a mockMvc get request, I receive a null result when requesting to get a JSON object. I have it that I can create a post fine, but struggling to receive data when invoking a GET endpoint in my controller.

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));
    }
  • The Controller endpoint and the request is fine.
  • There is data in the database.
  • It works WITHOUT the @MockBean , but then my post actually inserts data into the database. (Which isn't what I want)
  • I have tried to @InjectMocks , no luck.

Where am I going wrong? Do I have the correct annotations?

By mocking your bean, you'll get all its results as null.

You have 2 options,

  1. You continue to mock but you define behaviors using when/then
  2. You spy your bean: then it will do "the same" as normal and you can just stub the method you don't want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM