Mockito:当调用方法A.a然后执行B.b. [英] Mockito: when Method A.a is called then execute B.b

查看:604
本文介绍了Mockito:当调用方法A.a然后执行B.b.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito进行JUnit测试。
因此,我想要测试的代码中使用了给定的A类:

I'm using Mockito for JUnit tests. So there is a given class A that is used from the code i want to test:

class A{

    public A(){}

    public final String a(String x){
        return "A.a: " + x;
    }

}

我想替换方法使用相同的参数和相同类型的返回值调用另一个方法调用Aa。正如您所看到的,不可能通过扩展类来覆盖方法a,因为它是最终的。所以我现在拥有的另一个B类方法是Bb:

and i want to replace the Method call A.a with another method call with the same arguments and same type of return value. As you can see, its not possible to override the method a by extending the class as it is final. So what i have now is another class B with the method B.b:

class B{

    public B(){}

    public String b(String x){
        return "B.b: " + x;
    }

}

现在我想确保每一个从代码中调用Aa的时间,代替使用Bb的返回值。是否有可能通过Mockito实现这一点(类似 Mockito.when(Aa(x))。thenReturn(Bb(x)); )但是使用相同的参数x ,不知道x的价值?

Now i want to make sure every time when A.a is called from the code, the return value of B.b is used instead. Is there a possibility to achieve this with Mockito (something like Mockito.when(A.a(x)).thenReturn(B.b(x)); ) but with the same parameter x, without knowing the value of x?

任何帮助都将不胜感激,谢谢你提前!

Any help would be appreciated, thank you in advance!

推荐答案

根据 Mockito限制。但您可以使用 Powermock 在运行时破解代码,以便Mockito可以完成其工作。

It isn't possible to override final methods for Mockito-generated mocks, according to Mockito limits. But you can use Powermock to hack code at runtime so that Mockito can do its job.

这篇关于Mockito:当调用方法A.a然后执行B.b.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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