MockMvc perform(post())测试失败,并出现NullPointerException

时间:2020-10-07 22:41:37

标签: spring spring-boot nullpointerexception mockito mockmvc

我有以下控制器

@RequestMapping("/locations")
@AllArgsConstructor
@RestController
public class LocationController {

    private final LocationService locationService;

    @PostMapping
    public ResponseEntity<LocationDTO> createLocation(@Valid @RequestBody LocationDTO locationDTO) {

        Location location = locationService.createLocation(toLocation(locationDTO));

        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                                             .path("/{id}")
                                             .buildAndExpand(location.getId())
                                             .toUri();

        return ResponseEntity.created(uri).body(toDTO(location));
    }

    //other methods
}

和测试

@WebMvcTest(LocationController.class)
class LocationControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private LocationService locationService;

    @MockBean
    private MappingMongoConverter mappingMongoConverter;

    @WithMockUser(value = "test")
    @Test
    void createLocation() throws Exception {

        GeoJsonPoint testGeoJsonPoint = new GeoJsonPoint(123, 123);
        LocationProperties testLocationProperties = new LocationProperties("testName", "testDesc");
        Location testLocation = new Location("testId", testGeoJsonPoint, testLocationProperties);
        String locationDTOString = objectMapper.writeValueAsString(toDTO(testLocation));

        mvc.perform(post("/locations")
                .contentType(APPLICATION_JSON)
                .content(locationDTOString)
                .characterEncoding("utf-8"))
           .andDo(print())
           .andExpect(status().isCreated())
           .andExpect(content().contentType(APPLICATION_JSON))
           .andExpect(content().json(locationDTOString))
           .andExpect(header().string("uri", "http://localhost:8080/api/locations/testId"));
    }
}

测试结果: 解决的异常:类型= java.lang.NullPointerException

java.lang.AssertionError:预期状态:<201>但为:<500> 预期:201 实际:500

似乎是Location location = locationService.createLocation(toLocation(locationDTO));此位置设置为null。我该如何解决?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

模拟的LocationService可能返回null(在我的测试中确实如此)。对于此测试,LocationService应该是Location Service的真实实例,而不是模拟。

答案 1 :(得分:0)

因为它是一个模拟Bean,所以我不得不模拟服务的行为

when(locationService.createLocation(any())).thenReturn(testLocation);