Spring boot 使用MockMvc测试控制器时获取空指针

Spring boot 使用MockMvc测试控制器时获取空指针,spring-boot,spring-mvc,mockito,Spring Boot,Spring Mvc,Mockito,在对控制器进行单元测试时,我得到一个空指针。调用模拟服务以获取id时,控制器中出现空指针。我尝试了很多方法,但仍然出现相同的错误 以下是发生空指针的控制器代码片段: @RestController @RequestMapping(ELEMENTS_BASE_URI) @EnableCommonRestHeaders public class ElementController { @Autowired private ElementService elementService;

在对控制器进行单元测试时,我得到一个空指针。调用模拟服务以获取id时,控制器中出现空指针。我尝试了很多方法,但仍然出现相同的错误

以下是发生空指针的控制器代码片段:

@RestController
@RequestMapping(ELEMENTS_BASE_URI)
@EnableCommonRestHeaders
public class ElementController {
    @Autowired
    private ElementService elementService;
...
public ResponseEntity<ElementDto> createElement(
            @Valid @RequestBody ElementDto elementDto) {

        ElementDto saved = elementService.createElement(elementDto);

        HttpHeaders headers = new HttpHeaders();

        URI location = UriBuilder.builder(ELEMENT_LINK_URI)
                .pathVariable(ELEMENT_ID, saved.getId())
                .create();
        headers.setLocation(location);

        return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
    }
...

}
测试代码如下所示:

import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonObject;
import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonPath;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = ElementController.class, excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
@ActiveProfiles(value = {"test", "hsql", "disable-oauth2"})
@TestPropertySource("classpath:/test.properties")
public class ElementControllerTest {


    @MockBean
    private ElementService elementService;

    @Autowired
    ElementController elementController;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(elementController)
                .build();
    }

    @Test
    public void testCreateElementSuccess() throws Exception {
        ElementDto element = new ElementDto();
        element.setName("firstname");
        element.setModifiedTimeStamp(new Date());

        ElementDto createdElement = new ElementDto();
        String elementId = "123";
        createdElement.setId(elementId);
        createdElement.setName("firstname");
        createdElement.setLabel("firstname");
        createdElement.setAttribute(true);
        createdElement.setKeep(true);


        when(elementService.create(element)).thenReturn(createdElement);

        // make sure returns location with new element id
        mockMvc.perform(
                post(ServiceConstants.ELEMENTS_BASE_URI)
                     .content(mapper.writeValueAsBytes(element))
                     .accept(ElementDto.MEDIA_TYPE_JSON_VALUE)
                     .contentType(ElementDto.MEDIA_TYPE_JSON_VALUE))
                     .andExpect(status().isCreated())
                     .andExpect(header().string("Location",
                        Matchers.endsWith(ServiceConstants.SERVICE_URI + ServiceConstants.ELEMENTS_BASE_URI + "/" + elementId)))
                     .andExpect(header().string("Last-Modified", not(isEmptyString())))
                     .andExpect(jsonObject().is(createdElement))
                     .andExpect(jsonPath("name").value(element.getName()))
                     .andReturn();
    }
}
该行:

when(elementService.create(element)).thenReturn(createdElement);
似乎没有任何效果。非常感谢您在这方面的帮助

问候,,
Firas

这个问题的原因是我犯了一个错误。函数是createElement,when/any引用了create函数

我改变了:

when(elementService.create(eq(element))).thenReturn(createdElement);
致:


其余代码和符号正确。

因为测试中的
ElementDto
和控制器中的
ElementDto
将不是同一个实例。我怀疑您想要使用:
when(elementService.create(Mockito.any()).thenReturn(createdElement)@AlanHay,我将其替换为以下行:when(elementService.create(Mockito.any())。然后return(createdElement);我还是犯了同样的错误。谢谢。我也尝试了以下方法,但仍然存在相同的问题:when(elementService.create(Mockito.any(ElementDto.class))。然后return(createdElement);什么是真正为空的,服务还是创建的项?您的模拟注释看起来是错误的。请参见此处的示例:@AlanHay正如我在问题中提到的,空值发生在此行:ElementDto saved=elementService.createElement(ElementDto);保存的值为空。我不知道你的意思,我的模仿符号是错的。它们是标准的测试注释。
when(elementService.create(eq(element))).thenReturn(createdElement);
when(elementService.createElement(eq(element))).thenReturn(createdElement);