Junit Powermock模拟静态方法的问题

时间:2016-02-05 12:32:26

标签: java junit mockito powermock powermockito

这是我第一次尝试使用JUnit,并以某种方式解决了这个问题。

以下是我必须测试的类的结构:

public class ClassA extends AbstractClassA {

        @Override
    public java.lang.AutoCloseable createInstance() {
        ClassC provider = new ClassC();
        ...
        /*Following line is the problematic area - Class A invoking the static method of Class B with some parameters*/
        ClassB.init(getPort(),getConnectorUsername(),getConnectorPassword(),schemaRegistry,schemaContextFactory,getDefaultRequestTimeoutMillis(),bundleContext,domBroker,bindingBroker,getClientDispatcherDependency());
        return provider;
    }

我正在编写一个junit测试用例,用于测试createInstance,如下所示:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ClassB.class,
                     ClassA.class})
    public class ClassATest {

        @Test
        public void testCreateInstance() throws Exception {
            // configure mocks
            DependencyResolver dependencyResolver = mock(DependencyResolver.class);
            BindingAwareBroker bindingAwareBroker = mock(BindingAwareBroker.class);

            when(dependencyResolver.resolveInstance(eq(BindingAwareBroker.class), any(ObjectName.class), any(JmxAttribute.class))).thenReturn(bindingAwareBroker);

            // create instance of module with injected mocks
            ClassA module = new ClassA(mock(ModuleIdentifier.class), dependencyResolver);

            // Approach 1 to - Mock the ClassB' static method, stub init() to return 
            //PowerMockito.mockStatic(ClassB.class);
            //PowerMockito.doNothing().when(ClassB.class, "init", anyInt(), anyString(), anyString(), any(SchemaSourceRegistry.class), any(SchemaContextFactory.class), anyLong(), 
            //      any(BundleContext.class), any(Broker.class), any(BindingAwareBroker.class), any(NetconfClientDispatcher.class));

            /* Approach 2 to - Mock the ClassB' static method, stub init() to return 
            //PowerMockito.spy(ClassB.class);
            //PowerMockito.doNothing().when(ClassB.class);
            //ClassB.init(anyInt(), anyString(), anyString(), any(SchemaSourceRegistry.class), any(SchemaContextFactory.class), anyLong(), 
            //      any(BundleContext.class), any(Broker.class), any(BindingAwareBroker.class), any(NetconfClientDispatcher.class));*/

            // getInstance calls resolveInstance to get the broker dependency and then calls createInstance
            AutoCloseable closeable = module.getInstance();


        }
    }

我的问题是如何正确地做到这一点。 module.createInstance在方法中调用ClassB.init时引发NUll指针异常。 如果我从Class.createInstance中注释ClassB.init方法,则测试通过,这意味着我没有正确地嘲笑它。

我使用了两种方法进行模拟,因为init是一个静态方法,但它们都没有工作。

有人可以指出这个问题的根本原因,或者在编写JUnit测试时如何处理这类问题?

0 个答案:

没有答案