模拟多次调用的静态方法 [英] Mocking static method that is called multiple times

查看:114
本文介绍了模拟多次调用的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态方法,该方法在多个地方使用,主要是在静态初始化块中使用.它以Class对象为参数,并返回该类的实例. 我只想在将特定的Class对象用作参数时模拟此静态方法.但是,当从其他地方使用不同的Class对象调用该方法时,它将返回null.
如果参数不是模拟参数,我们如何让静态方法执行实际的实现?

I have a static method, that is used in multiple places, mostly in static initialization block. It takes a Class object as parameter, and returns the class's instance. I want to mock this static method only when particular Class object is used as parameter. But when the method is called from other places, with different Class objects, it returns null.
How can we have the static method execute actual implementation in case of parameters other than the mocked one?

class ABC{
    void someMethod(){
        Node impl = ServiceFactory.getImpl(Node.class); //need to mock this call
        impl.xyz();
    }
}

class SomeOtherClass{
    static Line impl = ServiceFactory.getImpl(Line.class); //the mock code below returns null here
}


class TestABC{
    @Mocked ServiceFactory fact;
    @Test
    public void testSomeMethod(){
         new NonStrictExpectations(){
              ServiceFactory.getImpl(Node.class);
              returns(new NodeImpl());
         }
    }
}

推荐答案

您想要的是一种部分模拟"形式,特别是 dynamic 部分模拟:

What you want is a form of "partial mocking", specifically dynamic partial mocking in the JMockit API:

@Test
public void testSomeMethod() {
    new NonStrictExpectations(ServiceFactory.class) {{
        ServiceFactory.getImpl(Node.class); result = new NodeImpl();
    }};

    // Call tested code...
}

只有与记录的期望匹配的调用才会被嘲笑.当调用动态模拟的类时,其他人将执行真实的实现.

Only the invocations that match a recorded expectation will get mocked. Others will execute the real implementation, when the dynamically mocked class is called.

这篇关于模拟多次调用的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆