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

标签 java testing junit mockito

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

我想将此行为扩展到任何整数(不一定是 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)

更新

导入:

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():

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

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

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

编辑: 您必须导入:

import static org.mockito.Matchers.anyInt;

关于java - 为任何整数输入参数设置模拟返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155369/

相关文章:

angular - 在 Angular e2e( Protractor )测试期间记录浏览器错误和网络流量

使用单独的数据服务器测试 apollo graphql 容器

testing - 使用 Karma 运行从外部 Web 服务器提供的 QUnit 测试

java - 将 JUnit 样式的 XML 测试输出渲染为 HTML

java - 如果我的测试中有验证,那么期望是多余的吗?

java - 返回 double 值作为非科学字符串

Java - 将 OutputStream 上传为 HTTP 文件上传

java - 如何配置此 Spring-Boot 应用程序以使用 IAM 角色而不是 key 和 secret ?

java - 在静态方法中模拟 UrlEncoder

java - 如何在 Java 中形成 UNIX 命令的 String[]?