为任何整数输入参数设置模拟返回值 [英] set mock return value for any integer input parameter

查看:177
本文介绍了为任何整数输入参数设置模拟返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如果我wrire

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

我有编译错误


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

The method findById(Integer) in the type CandidateService is not applicable for the arguments (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;


推荐答案

尝试anyInt():

Try anyInt():

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

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

For example I have anyLong() in my project:

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

编辑:
您必须导入:

You must import:

import static org.mockito.Matchers.anyInt;

这篇关于为任何整数输入参数设置模拟返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆