When testing with mockit or powermock, you can simulate the call to the System.exit(0) method through the Mock System class. The implementation steps are as follows:
Test using Mockit
The code to test using the Mockit framework is as follows:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mockit.Expectations;
import mockit.Mocked;
public class ExampleTest {
@Test
public void testMainMethod(@Mocked System system) {
new Expectations() {{
System.exit(0);
}};
Example.main(new String[] {});
assertEquals("测试失败", true, true);
}
}
在@Test注解的方法中,通过@Mocked注解来mock System类。
在Expectations对象中,设置期望的方法调用,即System.exit(0)。
调用Example类中的main方法,并使用assertEquals方法来判断测试是否通过。
Test with PowerMock
The code to test using the PowerMock framework is as follows:
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
@PowerMockIgnore({"javax.management.*"})
public class ExampleTest {
@Test
public void testMainMethod() {
mockStatic(System.class);
Example.main(new String[] {});
verifyStatic(System.class);
System.exit(0);
assertEquals("测试失败", true, true);
}
}
使用@RunWith注解指定使用PowerMockRunner运行测试。
使用@PrepareForTest注解来指定需要mock的类,这里是System类。
使用mockStatic方法来mock System类。
调用Example类中的main方法。
使用verifyStatic方法来验证System.exit(0)方法是否被调用。
使用assertEquals方法来判断测试是否通过。
Note:
PowerMock依赖于JUnit4运行测试。
@PowerMockIgnore注解可以用来忽略掉PowerMock不兼容的类或包,如上面代码中的"javax.management.*"。
@PrepareForTest注解需要指定需要mock的类,这里是System类,其他需要mock的类也需要在这里指定。