Class 测试中的 PowerMocking 静态方法

PowerMocking Static method within Class Under Test

我目前正在为使用静态方法实现的退出代码管理器实现单元测试。我遇到的问题是如何模拟调用 System.exit() 方法的 executeExit,这样它就不会终止所有的测试。

我尝试监视 SampleClass,但是每当我 运行 测试时它仍然继续退出程序。我尝试的另一个解决方案是模拟整个 class 并将 doCallRealMethod 用于被测方法。然而,这个解决方案是错误的,因为 (1) class 被测试没有进行代码覆盖,(2) 它以某种方式测试模拟的 class 而不是真正的 class 被测试。我也试过模拟 System.class 但它也不起作用。

非常感谢各种帮助。谢谢!

下面是一个类似于我们的方法结构的示例代码。

public class SampleClass{

    public static void methodA(){
        //do something here
        executeExit();

    public static void executeExit(){
        //doing some stuff
        System.exit(exitCode);
    }
}

下面是我如何 运行 我的测试的示例代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(SampleClass)
public class SampleClassTest {

    @Test
    public void testMethodA(){
        PowerMockito.spy(SampleClass.class);
        PowerMockito.doNothing().when(SampleClass.class,"executeExit");

        SampleClass.methodA();
    }
}

我会像这样测试你的代码:

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class SampleClassTest {

    @Rule
    ExpectedSystemExit exit = ExpectedSystemExit.none();

    @Test
    public void testMethodA() {

        exit.expectSystemExitWithStatus(-1);
        SampleClass.methodA();
    }
}

您需要以下依赖项

<dependency>
    <groupId>com.github.stefanbirkner</groupId>
    <artifactId>system-rules</artifactId>
    <version>1.16.1</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
        </exclusion>
    </exclusions>
</dependency>

或者如果您不想导入该依赖项,您可以这样做:

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({ SampleClass.class })
public class SampleClassTest {


    @Test
    public void testMethodA() {

        PowerMockito.spy(SampleClass.class);
        PowerMockito.doNothing().when(SampleClass.class);
        SampleClass.executeExit();

        SampleClass.methodA();

        PowerMockito.verifyStatic();
        SampleClass.executeExit();

    }
}