【问题标题】:How to mock another static method in the same class which is being tested?如何在正在测试的同一类中模拟另一个静态方法?
【发布时间】:2017-08-25 14:17:28
【问题描述】:

我正在使用 Mockito 为具有两个方法 methodA、methodB 的类编写 JUnit 测试用例。我想在我的测试用例中模拟从methodB对methodA的调用。有人帮助我。请

这是课程:

public Class Test{
    public static List<Object> methodA() {
        ...
        return list;    
    }

    public static List<Object> methodB() {
        ...
        list = methodA();
        return list;
    }
}

【问题讨论】:

  • 使用“when”模拟方法调用
  • 首先...为什么?为什么会有这个静态方法?想想看。再次。再次。如果您需要模拟这个静态方法,听起来这个静态方法实际上是一个依赖项,应该进入它自己的类(使用非静态方法),以便可以轻松地模拟它。必须模拟静态方法是一种代码异味(这意味着它可能表明有问题的代码很糟糕)。

标签: unit-testing mockito


【解决方案1】:

您将需要使用 PowerMockito 来模拟静态方法。

例子:

package unitest;

import java.util.ArrayList;
import java.util.List;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest(unitest.Test.class)
public class TestTest {

    @Test
    public void testMethodB() {
        PowerMockito.mockStatic(unitest.Test.class);
        PowerMockito.when(unitest.Test.methodA()).thenReturn(new ArrayList());
        List b = unitest.Test.methodB();
        org.junit.Assert.assertNotNull(b);
    }

}

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2021-11-19
    • 2022-06-19
    • 2021-09-17
    • 2011-08-13
    • 2021-10-11
    相关资源
    最近更新 更多