使用Mockito在方法调用上拦截对象 [英] Intercept object on method invocation with Mockito

查看:138
本文介绍了使用Mockito在方法调用上拦截对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有void方法的模拟类,如

I've a mocked class with a void method like

public class Mock {
    public void method(String string) {
        // doSomething
    }
}

我不关心这个方法做了什么,但我想要发送String。

I don't care about what this method does but I would like to get the String sent.

这个String实际上是一个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);
}

我想看看之前为null的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在方法调用上拦截对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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