如何使用PowerMockito测试两个静态方法(一个调用另一个)? [英] How can I test two static methods (one invokes the other) with PowerMockito?

查看:803
本文介绍了如何使用PowerMockito测试两个静态方法(一个调用另一个)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试第一个静态方法方法(字符串str,参数param)

How can I test the first static method method(String str, Param param)?

public class Example {

    public static Example method(String str, Param param) {
        return method(str, param, null);
    }

    private static Example method(String str, Param param, SomeClass obj) {
        // ...
    }
}

我尝试使用以下代码对其进行测试

I try to test it with code below

@Test
public void should_invoke_overloaded_method() throws Exception {

    final String str  = "someString";    
    mockStatic(Example.class);

    when(Example.method(str, paramMock))
            .thenCallRealMethod();

    when(Example.method(str, paramMock, null))
            .thenReturn(expectedMock);

    Example.method(str, paramMock);
    verifyStatic();
}

但是没有运气。例如,如何修复此测试以验证第二种方法的调用?

But with no luck. How can I fix for example this test to verify invocation of the second method?

推荐答案

此代码有效:

import static org.junit.Assert.assertSame;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
    @Test
    public void should_invoke_overloaded_method() throws Exception {
        final String str = "someString";
        Param paramMock = mock(Param.class);
        Example expectedMock = mock(Example.class);

        mockStatic(Example.class);

        when(Example.method(str, paramMock)).thenCallRealMethod();
        when(Example.class, "method", str, paramMock, null).thenReturn(expectedMock);

        assertSame(expectedMock, Example.method(str, paramMock));
    }
}

这篇关于如何使用PowerMockito测试两个静态方法(一个调用另一个)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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