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