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

18 java testing junit mockito

when(candidateService.findById(1)).thenReturn(new Candidate());
Run Code Online (Sandbox Code Playgroud)

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

如果我啰嗦

when(candidateService.findById( any(Integer.class)  )).thenReturn(new Candidate());
Run Code Online (Sandbox Code Playgroud)

我有编译错误

CandidateService类型中的方法findById(Integer)不适用于参数(Matcher)

UPDATE

进口:

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.HashSet;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
Run Code Online (Sandbox Code Playgroud)

Ern*_*zys 35

尝试anyInt():

when(candidateService.findById(anyInt())).thenReturn(new Candidate());
Run Code Online (Sandbox Code Playgroud)

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

when(dao.getAddress(anyLong())).thenReturn(Arrays.asList(dto));
Run Code Online (Sandbox Code Playgroud)

编辑:您必须导入:

import static org.mockito.Matchers.anyInt;
Run Code Online (Sandbox Code Playgroud)