java – 为任何整数输入参数设置模拟返回值

前端之家收集整理的这篇文章主要介绍了java – 为任何整数输入参数设置模拟返回值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. when(candidateService.findById(1)).thenReturn(new Candidate());

我想扩展这种行为为任何整数(不一定为1)

如果我吃惊

  1. when(candidateService.findById( any(Integer.class) )).thenReturn(new Candidate());

我有编译错误

The method findById(Integer) in the type CandidateService is not
applicable for the arguments (Matcher)

UPDATE

进口:

  1. import static org.junit.Assert.assertEquals;
  2. import static org.mockito.Matchers.anyInt;
  3. import static org.mockito.Matchers.anyString;
  4. import static org.mockito.Mockito.mock;
  5. import static org.mockito.Mockito.times;
  6. import static org.mockito.Mockito.verify;
  7. import static org.mockito.Mockito.when;
  8. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  9.  
  10. import java.util.ArrayList;
  11. import java.util.HashSet;
  12.  
  13. import org.junit.Before;
  14. import org.junit.Test;
  15. import org.junit.runner.RunWith;
  16. import org.mockito.InjectMocks;
  17. import org.mockito.Mock;
  18. import org.mockito.MockitoAnnotations;

解决方法

尝试anyInt():
  1. when(candidateService.findById( anyInt())).thenReturn(new Candidate());

例如我的项目中有anyLong():

  1. when(dao.getAddress(anyLong())).thenReturn(Arrays.asList(dto));

编辑:
您必须导入:

  1. import static org.mockito.Matchers.anyInt;

猜你在找的Java相关文章