java - Mockito 显示 0 次与 mock 的交互
问题描述
这是我的代码:
public class S3Dao {
private final AmazonS3Client amazonS3Client;
static final String BUCKET_NAME = "myBucket";
public S3Dao(final AmazonS3Client amazonS3Client) {
this.amazonS3Client = amazonS3Client;
}
public void put(ModelObject modelObject, String playlistId) {
this.amazonS3Client.putObject(BUCKET_NAME, playlistId, new Gson().toJson(modelObject));
}
}
还有我的测试代码:
@ExtendWith(MockitoExtension.class)
public class S3DaoTest {
private S3Dao s3Dao;
@Mock
private AmazonS3Client s3Client;
@BeforeEach
public void beforeEach() {
this.s3Dao = new S3Dao(this.s3Client);
}
@Test
public void putTest() {
ModelObject obj = new ModelObject("name", new ArrayList<>());
String json = new Gson().toJson(obj);
verify(s3Client).putObject(S3Dao.BUCKET_NAME, "playlistId", json);
this.s3Dao.put(obj, "playlistId");
}
}
产生的错误是
Wanted but not invoked:
s3Client.putObject(
"myBucket",
"playlistId",
"{"name":"name","children":[]}"
);
-> at com.amazon.amazon.live.destination.playlist.dao.S3DaoTest.putTest(S3DaoTest.java:34)
Actually, there were zero interactions with this mock.
实际上,删除验证会导致测试顺利通过。为什么这不起作用?
解决方案
在方法调用之后移动验证
@Test
public void putTest() {
ModelObject obj = new ModelObject("name", new ArrayList<>());
String json = new Gson().toJson(obj);
this.s3Dao.put(obj, "playlistId");
verify(s3Client).putObject(S3Dao.BUCKET_NAME, "playlistId", json);
}
推荐阅读
- excel - VBA 在 word 中查找和替换。用数字和单词之间的不间断空格替换空格
- sql - EF Core 插入操作 - SQL 命令如何工作?
- json - 当值为整数时,不能将小数部分显示为 .0
- nix - 在 nix 包中设置标志
- angular - 如何使用数据从另一个网站重定向到 Angular 应用程序?
- python - 如何使 admin.TabularInline 中的字段之一成为条件?
- android - Google 登录 OAuth、后端服务器身份验证和令牌每日限制
- c - 如何对我的随机生成器函数进行单元测试?
- numpy - Matplotlib x 轴乱序绘制
- mysql - 用sql分割字符串