简体   繁体   English

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

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

I am facing problem while testing method using Mockito.我在使用 Mockito 测试方法时遇到问题。 please check testMethodToBeTested() method of JunitTestCaseClass, which has to handle static method call of thirdparty class.请检查 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);
    }
}

Please help & Thanks in Advance.请帮助并提前致谢。

I think this is your answer why it is not working: https://github.com/mockito/mockito/wiki/FAQ我认为这就是为什么它不起作用的答案: https : //github.com/mockito/mockito/wiki/FAQ

What are the limitations of Mockito Mockito 的局限性是什么

Mockito 2.x specific limitations Mockito 2.x 特定限制

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

Firstly, you should not mock those methods.首先,你不应该嘲笑这些方法。 Secondly, Mockito defines and depends upon a specific implementation of these methods.其次,Mockito 定义并依赖于这些方法的特定实现。 Redefining them might break Mockito.重新定义它们可能会破坏 Mockito。 Mocking is only possible on VMs that are supported by Objenesis.模拟只能在 Objenesis 支持的 VM 上进行。 Don't worry, most VMs should work just fine.别担心,大多数虚拟机应该可以正常工作。 Spying on real methods where real implementation references outer Class via OuterClass.this is impossible.监视真正的方法,其中真正的实现通过 OuterClass.this 引用外部 Class 是不可能的。 Don't worry, this is extremely rare case.别担心,这是极其罕见的情况。

If you really want to mock static methods then PowerMock is your solution.如果您真的想模拟静态方法,那么PowerMock是您的解决方案。 https://github.com/powermock/powermock/wiki/mockito https://github.com/powermock/powermock/wiki/mockito

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

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