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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19155369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:34:49  来源:igfitidea点击:

set mock return value for any integer input parameter

javatestingjunitmockito

提问by

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

I want to extend this behaviour for any Integer(not necessarily for 1)

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

If I wrire

如果我写

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

I have compilation error

我有编译错误

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

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

UPDATE

更新

imports:

进口:

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;

采纳答案by Ernestas Kardzys

Try anyInt():

试试 anyInt():

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

For example I have anyLong() in my project:

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

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

EDIT: You must import:

编辑:您必须导入:

import static org.mockito.Matchers.anyInt;