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 进行方法调用时拦截对象


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01