spring-boot - 使用 MockMvc 测试控制器时获取空指针
问题描述
在对控制器进行单元测试时,我得到一个空指针。调用模拟服务以获取 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);
}
...
}
在上面的控制器代码中,空指针出现在下面一行:saveed is null
ElementDto saved = elementService.createElement(elementDto);
测试代码如下:
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);
似乎没有任何效果。对此的任何帮助都非常感谢。
问候, 菲拉斯
解决方案
这个问题的原因,是我犯的一个错误。该函数是 createElement 并且 when/any 引用了 create 函数。
我变了:
when(elementService.create(eq(element))).thenReturn(createdElement);
至:
when(elementService.createElement(eq(element))).thenReturn(createdElement);
其余代码和符号是正确的。
推荐阅读
- xml - 如果xml中缺少标签,为什么会显示文本?
- linq - 在 LINQ 中对多个表进行分组计数
- sql - 从 SELECT 语句中插入多行以及另一列中的数组
- formio - 删除超过 n 天的 form.io 提交
- amazon-web-services - 是否有一种简单的方法可以将 GUI 搜索元素添加到 AWS cloudwatch 仪表板?
- python-3.x - XML 请求格式不正确或请求不完整调用 Elavon api 生成令牌
- python - 检查嵌套列表是否包含子字符串
- windows - 如何在系统关闭时使用 PowerShell 运行一些代码?
- java - ImageIO.write 的写入器无效
- javascript - 通过 php POST 发送的关联数组不完整