【问题标题】:JUnit: Intercepting a method call and then invoking with different paramsJUnit:拦截方法调用,然后使用不同的参数调用
【发布时间】:2016-08-17 10:33:14
【问题描述】:

我正在研究 junit 并使用 PowerMockRunner 来模拟静态方法。

我知道可以使用when(...).thenReturn(...) 模拟静态方法

我需要模拟一个接受四个参数的方法:

public static void addInputPath(String, Boolean, Integer, Double)

我需要将此方法的任何调用中的第三个参数(整数)替换为10。所有其他参数都应该按原样传递。

换句话说,我需要做这样的事情:

when(addInputPath(str, bool, intgr, dbl)).thenReturn(addInputPath(str, bool, 10, dbl));

有没有办法做到这一点?

【问题讨论】:

标签: java unit-testing junit powermock


【解决方案1】:

那么,当我满足您的要求时,您真正想要做的是拦截对 addInputPath() 的调用并使用不同的参数调用它?

如果是这样:我不确定这是否可以使用任何模拟框架来完成(我怀疑这是可能的)。模拟框架是关于模拟调用;与检测/拦截呼叫无关。

回到你的问题,这是一个很好的例子,为什么 static 调用经常会导致问题。因此,在我看来,最好的解决方案是更改您的方法 xyz() 以避免直接调用 addInputPath() 。像这样:

interface InputPathAdder {
   void addInputPath(str, ... );
}

class ForwardingInputPathAdder implements InputPathAdder {
   // implements the method by calling the static method

突然之间,你也可以这样做:

class ForwardingInputPathAdderWithFixedIntegerParm implements InputPathAdder {
   // implements the method by calling the static method, but using 10 always

(显然,这里的命名可以改进)

现在:您使用依赖注入来为您的“被测类”提供一些实现 InputPathAdder 的对象。这可能是完全模拟测试的一种;或者它可能只是转发(在您的生产环境中;或者它可能是修复第三个参数的那个)。并且不需要嘲笑你的“拦截”情况。

【讨论】:

    猜你喜欢
    • 2014-10-11
    • 2021-09-16
    • 2012-04-01
    • 1970-01-01
    • 2014-08-06
    • 2012-08-18
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多