【问题标题】:How to handle Static method call of ThirdParty class while junit testing using Mockito?使用Mockito进行junit测试时如何处理ThirdParty类的静态方法调用?
【发布时间】:2020-01-28 11:27:58
【问题描述】:

我在使用 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);
    }
}

请帮助并提前致谢。

【问题讨论】:

    标签: java mockito junit4


    【解决方案1】:

    我认为这是您为什么它不起作用的答案: 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 引用外部类是不可能的。别担心,这种情况非常罕见。

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

    【讨论】:

      猜你喜欢
      • 2023-02-13
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多