Intercept object on method invocation with Mockito(在使用 Mockito 进行方法调用时拦截对象)
问题描述
我有一个类似 void 方法的模拟类
I've a mocked class with a void method like
public class Mock {
public void method(String string) {
// doSomething
}
}
我不关心这个方法的作用,但我想发送字符串.
I don't care about what this method does but I would like to get the String sent.
这个字符串实际上是一个 JSON 格式的对象,我正在测试的方法是根据最初发送的字符串修改这个对象(假设是非常随机的).
This String is actually an object in a JSON format, and the method that I'm testing is modifying this object depending on the String originally sent (quite random let's say).
method(String json) {
Object obj = unparse(json);
obj.setRandomValue(random);
String parsed = parse(obj);
Mock.method(parsed);
}
我只是想看看之前为空的randomValue"是否在方法调用后实际上设置为随机数.
I would like just to see if the "randomValue", previously null, is actually set with the random after the method invocation.
最好的办法是截取 json,解析它并检查对象.
The best would be to intercept the json, parse it and check the object.
推荐答案
您正在寻找一个 ArgumentCaptor:
You are looking for an ArgumentCaptor:
Mock mock = Mockito.mock(Mock.class);
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
mock.method("input");
Mockito.verify(mock).method(captor.capture());
String actualValue = captor.getValue();
这篇关于在使用 Mockito 进行方法调用时拦截对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在使用 Mockito 进行方法调用时拦截对象
基础教程推荐
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 Windows 证书导入 Java 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
