mockito返回空可选

pw136qt2  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(276)

我看到一个奇怪的问题,我的方法返回一个空的 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;
}

0s7z1bwu

0s7z1bwu1#

抱歉,伙计们,这是我的。问题是测试中的代码通过了 null 对于布尔值(我在上面的代码中错误地显示了有效值)和 Mockito.anyBoolean() 不接受 null . 修改为 Mockito.anyNull() 我成功了。

9njqaruj

9njqaruj2#

第一个参数应该使用anylong(),而不是anylist()。

相关问题