繁体   English   中英

使用Mockito进行junit测试时如何处理第三方类的静态方法调用?

[英]How to handle Static method call of ThirdParty class while junit testing using Mockito?

我在使用 Mockito 测试方法时遇到问题。 请检查 JunitTestCaseClass 的 testMethodToBeTested() 方法,该方法必须处理第三方类的静态方法调用。

class ClasssToBeTested{

    public String methodToBeTested() {
        String result = ThirdPartyUtilClass.methodToBeCall();
        return result;
    }
}

class ThirdPartyUtilClass{

    public static String methodToBeCall(){
        return "OK";
    }
}

// JunitTestCase which will test method "methodToBeTested()" of ClasssToBeTested class
class JunitTestCaseClass{

    @InjectMocks
    private ClasssToBeTested classsToBeTested;

    @Test
    public void testMethodToBeTested() {
        //How to handle ThirdPartyUtilClass.methodToBeCall(); statement in unit testing
        String result = classsToBeTested.methodToBeTested();
        Assert.assertNotNull(result);
    }
}

请帮助并提前致谢。

我认为这就是为什么它不起作用的答案: https : //github.com/mockito/mockito/wiki/FAQ

Mockito 的局限性是什么

Mockito 2.x 特定限制

Requires Java 6+
Cannot mock static methods
Cannot mock constructors
Cannot mock equals(), hashCode(). 

首先,你不应该嘲笑这些方法。 其次,Mockito 定义并依赖于这些方法的特定实现。 重新定义它们可能会破坏 Mockito。 模拟只能在 Objenesis 支持的 VM 上进行。 别担心,大多数虚拟机应该可以正常工作。 监视真正的方法,其中真正的实现通过 OuterClass.this 引用外部 Class 是不可能的。 别担心,这是极其罕见的情况。

如果您真的想模拟静态方法,那么PowerMock是您的解决方案。 https://github.com/powermock/powermock/wiki/mockito

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM