20
when(candidateService.findById(1)).thenReturn(new Candidate());

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

如果我写

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

我有编译错误

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

更新

进口:

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;
4

1 回答 1

43

试试 anyInt():

when(candidateService.findById(anyInt())).thenReturn(new Candidate());

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

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

编辑:您必须导入:

import static org.mockito.Matchers.anyInt;
于 2013-10-03T09:45:15.280 回答