有一个类,里面有main方法,main方法里面的最后调用了System.exit(0),如何用mockit或者powermock测试
使用Mockito测试System.exit(0)的方式如下:
import static org.mockito.Mockito.*;
@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来测试System.exit(0)可以通过以下步骤完成:
<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>
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);
}
}