【问题标题】:How to test REST controller using MockMvc如何使用 MockMvc 测试 REST 控制器
【发布时间】:2020-03-02 15:47:13
【问题描述】:

我已经尝试了一段时间来测试我的 REST 控制器端点,使用 MockMvcMockitoCucumber

  • 我的目标是在不调用实际实现的情况下测试我的服务层。 (所以我不希望数据出现在数据库中)

  • 在处理大型项目时,我想避免使用“内存中”数据库。

我最近让它工作,没有模拟,但自从我尝试模拟我的测试以来,我一直收到NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

AddressControllersn-p

@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);
}

AddressStepDefssn-p

@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));
    }

【问题讨论】:

    标签: java spring-boot mocking mockito integration-testing


    【解决方案1】:

    假设您使用的是最新版本的 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,恕我直言,这不是集成测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-25
      • 2013-01-11
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多