如何在使用 Mockito 进行 junit 测试时处理 ThirdParty class 的静态方法调用?
How to handle Static method call of ThirdParty class while junit testing using Mockito?
我在使用 Mockito 测试方法时遇到问题。
请检查 JunitTestCaseClass 的 testMethodToBeTested() 方法,它必须处理第三方的静态方法调用 class.
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 specific limitations
Requires Java 6+
Cannot mock static methods
Cannot mock constructors
Cannot mock equals(), hashCode().
首先,你不应该模拟那些方法。其次,Mockito 定义并依赖于这些方法的特定实现。重新定义它们可能会破坏 Mockito。
只能在 Objenesis 支持的 VM 上进行模拟。别担心,大多数 VM 应该都可以正常工作。
监视真正的方法,其中真正的实现通过 OuterClass.this 引用外部 Class 是不可能的。别担心,这种情况非常罕见。
如果您真的想模拟静态方法,那么 PowerMock 就是您的解决方案。
https://github.com/powermock/powermock/wiki/mockito
我在使用 Mockito 测试方法时遇到问题。 请检查 JunitTestCaseClass 的 testMethodToBeTested() 方法,它必须处理第三方的静态方法调用 class.
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 specific limitations
Requires Java 6+
Cannot mock static methods
Cannot mock constructors
Cannot mock equals(), hashCode().
首先,你不应该模拟那些方法。其次,Mockito 定义并依赖于这些方法的特定实现。重新定义它们可能会破坏 Mockito。 只能在 Objenesis 支持的 VM 上进行模拟。别担心,大多数 VM 应该都可以正常工作。 监视真正的方法,其中真正的实现通过 OuterClass.this 引用外部 Class 是不可能的。别担心,这种情况非常罕见。
如果您真的想模拟静态方法,那么 PowerMock 就是您的解决方案。 https://github.com/powermock/powermock/wiki/mockito