如何在java中模拟单个方法 [英] How to mock a single method in java

查看:96
本文介绍了如何在java中模拟单个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以模拟Java类的单个方法?

Is it possible to Mock a single method of a Java class?

例如:

class A {
    long method1();
    String method2();
    int method3();
}


// in some other class
class B {
    void someMethod(A a) {
       // how would I mock A.method1(...) such that a.method1() returns a value of my
       // choosing;
       // whilst leaving a.method2() and a.method3() untouched.
    }
}


推荐答案

使用 Mockito的间谍机制:

A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);

使用spy会为任何非存根的方法调用包装对象的默认行为。

The use of a spy calls the default behavior of the wrapped object for any method that is not stubbed.

Mockito.spy() / @ Spy

这篇关于如何在java中模拟单个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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