繁体   English   中英

使用 powermockito 模拟静态方法

[英]Mocking a static method using 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'.

我错过了什么? 我检查了很多关于这个问题的旧帖子,但没有任何对我有用。

工作示例在这里 使用 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'
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM