使用powermockito模拟静态方法

时间:2020-10-30 11:11:53

标签: java unit-testing mockito powermockito

我正在测试一些旧代码,并想模拟对静态记录器方法的任何调用:LoggerFact.getLogger(Class class, String MethodName),这是我尝试的方法:

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFact.class, MyClass.class, Logger.class})
public class MyClassTest
{
    @Before
    public void prepare() throws Exception
    {
      Logger mockedLogger = Mockito.mock(Logger.class);
      PowerMockito.mockStatic(LoggerFact.class);
      PowerMockito.when(LoggerFact.getLogger(MyClass.class, "test"))
                  .thenReturn(mockedLogger);
    }

    //My tests
}

我正在测试的课程:

public class MyClass
{
    public String methodToBeTested()
    {
      Logger logger = LoggerFact.getLogger(this.getClass(), "test");
      logger.info("This is a test");
      //some logic
      return "SUCCESS";
    }
}

但是当我从prepare when()执行此操作时,我收到此错误:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.

我错过了什么吗?我检查了很多有关此问题的较早的帖子,但没有任何帮助。

1 个答案:

答案 0 :(得分:0)

工作示例here。经过JDK 8和JDK 11的测试。

以下对我有用。 (我发现初始化的顺序很关键):

@RunWith(PowerMockRunner.class)
@PrepareForTest(LoggerFact.class)
public class MyClassTestCase {
    private MyClass myClass = null;

    @Before
    public void setUp() {
        PowerMockito.mockStatic(LoggerFact.class);
    }

    @Test
    public void testMethodToBeTested() {
        Logger mockLogger = Mockito.mock(Logger.class);

        PowerMockito.when(LoggerFact.getLogger(eq(MyClass.class),eq("test"))).thenReturn(mockLogger);
        myClass = new MyClass();

        // test
        myClass.methodToBeTested();

        verify(mockLogger, times(1)).info(eq("This is a test"));
    }
}

根据要求,从以上示例链接中的build.gradle,以下是库的版本:

dependencies {
    testImplementation 'junit:junit:4.13.1'
    testImplementation 'org.mockito:mockito-core:3.6.0'
    testImplementation 'org.powermock:powermock-api-mockito2:2.0.7'
    testImplementation 'org.powermock:powermock-module-junit4:2.0.7'
}