java System.exit(0)测试

有一个类,里面有main方法,main方法里面的最后调用了System.exit(0),如何用mockit或者powermock测试

Mockito测试

使用Mockito测试System.exit(0)的方式如下:

  1. 引入Mockito库。
import static org.mockito.Mockito.*;
  1. 在测试方法中,使用Mockito.mockStatic()方法来mock System类。
@Test
public void testSystemExit() {
    PowerMockito.mockStatic(System.class);

    // 测试System.exit(0)是否被调用
    MyMain.main(new String[]{});
    PowerMockito.verifyStatic(System.class, times(1));
    System.exit(0);
}

在这个例子中,使用了PowerMockito来mock System类,这是因为System类是一个静态类。然后,调用main方法并验证System.exit(0)是否被调用了一次。

需要注意的是,使用Mockito或PowerMockito进行静态方法mock的时候,要在测试类中添加@RunWith(PowerMockRunner.class)和@PrepareForTest注解,以启用PowerMockito的功能。

完整代码示例:


import static org.mockito.Mockito.*;

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(System.class)
public class MyMainTest {
    @Test
    public void testSystemExit() {
        PowerMockito.mockStatic(System.class);

        // 测试System.exit(0)是否被调用
        MyMain.main(new String[]{});
        PowerMockito.verifyStatic(System.class, times(1));
        System.exit(0);
    }
}

class MyMain {
    public static void main(String[] args) {
        // some code here
        System.exit(0);
    }
}

PowerMockito测试

使用PowerMockito来测试System.exit(0)可以通过以下步骤完成:

  1. 在pom.xml文件中添加PowerMockito和JUnit的依赖。
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.9</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.9</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

  1. 在测试类中使用PowerMockito来mock System类和System.exit方法。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;

@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class})
public class TestClass {
    @Test
    public void testMethod() {
        mockStatic(System.class);
        MyClass.main(new String[0]);
        verifyStatic(System.class);
        System.exit(0);
    }
}

  1. 在测试方法中,首先使用mockStatic方法来mock System类,然后调用被测试类的main方法,最后使用verifyStatic方法来验证System.exit方法是否被调用过。
    这样,就可以使用PowerMockito来测试System.exit(0)方法了。