![](/img/trans.png)
[英]How to Mock the void method call which is present inside static method using Mockito and 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.