【发布时间】:2021-02-08 04:50:13
【问题描述】:
我看到一个奇怪的问题,我的方法返回一个空的Optional,尽管使用mockito 进行模拟。可能出了什么问题?
我的测试:
@RunWith(SpringRunner.class)
@WebMvcTest(InfoController.class)
@ActiveProfiles("test")
public class InfoControllerTest
{
@Autowired
private MockMvc mockMvc;
@MockBean
private Service service;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testDeleteValueSet() throws JsonProcessingException, Exception
{
DeleteValueSetContainer c1 = new DeleteValueSetContainer();
c1.setValueSetIds(Collections.singletonList(1L));
Mockito.when(service.deleteValueSet(Mockito.anyList(),
Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Optional.of(new Info()));
mockMvc.perform(delete("/deleteValueSet").
accept(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(c1))
.contentType(MediaType.APPLICATION_JSON)).andExpect(status().isNoContent());
}
}
待测方法:
@DeleteMapping("/deleteValueSet")
public ResponseEntity<Long> deleteValueSet(@RequestBody(required=true) DeleteValueSetContainer
deleteValueSetContainer)
{
Optional<Info> optional = service.deleteValueSet(valueSetIds,
null, null);
if(optional.isPresent())
{
Info valueInformation = optional.get();
Long parentValueId = valueInformation.getParentValueId();
if(parentValueId != null && parentValueId != 0L)
{
return ResponseEntity.created(ServletUriComponentsBuilder.
fromCurrentRequest().build().toUri())
.body((Long)valueInformation.getParentValueId());
}
return ResponseEntity.noContent().build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
我最终得到 500 错误而不是 200,因为模拟没有按预期工作。
被模拟的方法:
public Optional<Info> deleteValueSet(List<Long> ids, Boolean char,
Boolean digit)
{
// Logic to populate Info
Info i = new Info();
return Optional.of(information);
}
Info 是服务中的公共静态内部类。
public static class Info
{
private Long parentValueId;
private Long id;
private Map<Long, Long> idInfos;
}
【问题讨论】:
-
deleteValueSet() 方法有 Long 参数。但是您已经在 mockito 中指定了 List 参数。我认为这就是错误所在。
-
对不起,我修改了方法签名。
-
如何在测试中分享您的
service初始化/模拟和 -
@Naman - 我在
Controller测试中使用了@MockBean private HelperService service
标签: java spring mockito optional