簡體   English   中英

如何使用 MockMvc 測試 REST 控制器

[英]How to test REST controller using MockMvc

我已經嘗試使用MockMvcMockitoCucumber來測試我的 REST 控制器端點已經有一段時間了。

  • 我的目標是測試我的服務層,而不調用實際的實現。 (所以我不希望數據出現在數據庫中)

  • 我想避免使用“內存中”數據庫,因為我正在處理一個大型項目。

我最近讓它在沒有模擬的情況下工作,但是自從我嘗試模擬我的測試以來,我一直收到NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

AddressController片段

@Autowired
private AddressManager addressManager;

@GetMapping(value = "/{id}")
public ResponseEntity<Object> getAddress(@PathVariable("id") Long addressId) {
    return new ResponseEntity<>(addressManager.getAddress(addressId), HttpStatus.OK);
// getAddress calls a data manager layer which then calls addressRepo.findOneById(addressId);
}

@PostMapping(value = "/add")
public ResponseEntity<Object> addAddress(@RequestBody Address address) {
    return new ResponseEntity<>(addressManager.addAddress(address), HttpStatus.OK);
// addAddress calls a data manager layer which then calls addressRepo.save(address);
}

AddressStepDefs片段

@RunWith(MockitoJUnitRunner.class) 
@SpringBootTest(webEnvironment= WebEnvironment.MOCK)
@Transactional
@AutoConfigureMockMvc
public class AddressStepDefs {

    private MockMvc mockMvc;

    private ResultActions result; // allows to track result

    @InjectMocks
    private AddressController addressController; 

    @Mock
    private AddressDataManager addressService;

   // given step

   @Before  
   public void setup() throws IOException {
       // must be called for the @Mock annotations to be processed and for the mock service to be injected 
       // into the controller under test.
      MockitoAnnotations.initMocks(this);
      this.mockMvc = MockMvcBuilders.standaloneSetup(new AddressController()).build(); 
   }

   @When("I add a new Address using POST at {string} with JSON:")
   public void i_add_a_new_Address_using_POST_at_with_JSON(String request, String json) throws Exception {
       /** Build a POST request using mockMvc **/
       result = this.mockMvc.perform(post(request).contentType(MediaType.APPLICATION_JSON)
                .content(json.getBytes()).characterEncoding("utf-8"));
    }

    @Then("the response code should be OK {int} and the resulting json should be:")
    public void the_response_code_should_be_OK_and_the_resulting_json_should_be(Integer responseCode, 
    String json) throws Exception {
        result.andExpect(status().is(responseCode));
        result.andExpect(content().string(json));
    }

    @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 **/
        result = this.mockMvc.perform(get(request + id).contentType(MediaType.APPLICATION_JSON));
    }

假設您使用的是最新版本的 Spring Boot(並且您還不需要 Cucumber),那么您只需要AddressStepDefs作為:

@WebMvcTest(AddressController.class)
public class AddressStepDefs {
  @MockBean
  private AddressDataManager addressService;

  @Autowired
  private MockMvc mvc;

  ...

  // Depending on how you configured your Spring beans, you might need this; try first without it ;)
  @Configuration
  @ComponentScan(basePackageClasses = AddressController.class)
  static class TestConfig {
    // ...will be used instead of the application's primary configuration
  }
}

@WebMvcTest注釋在這里對於您的用例很方便,因為它僅用於僅關注 Spring MVC 組件的 Spring MVC 測試。

那么給定的測試可以寫成:

@Test
void getAll_WhenRecordsExist() throws Exception { // HTTP 200 (OK)
  final Collection<Address> expected = Arrays.asList(AddressFactory.random(), AddressFactory.random());
  Mockito.when(addressService.searchAll()).thenReturn(expected);
  mvc.perform(get("/addresses").accept(MediaType.APPLICATION_JSON))
     // .andDo(MockMvcResultHandlers.print())
      .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
      .andExpect(status().isOk())
      .andExpect(content().json(mapper.writeValueAsString(expected))); // ...you need Jackson's object mapper injected also as part of a class' member
  Mockito.verify(service).searchAll();
}

如果您正在addressService這不是集成測試,恕我直言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM