0
Follow
0
View

java System.exit(0) test

dhcbobo 注册会员
2023-02-28 19:35


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的类也需要在这里指定。

About the Author

Question Info

Publish Time
2023-02-28 19:35
Update Time
2023-02-28 19:35

Related Question

Java编译出现错误Variable expected,怎样改

关于java面向对象的问题

在Powerapps中使用客户端API(JavaScript)创建SharePoint文档位置

关于#javascript#的问题,请各位专家解答!

从Javascript数组到HTML表(Arquero?Tidy.js吗?Data-Forge ?)

Java ClassCastException混淆

Java后期绑定和方法过载的问题

java判断三角形类型并计算三角形面积

问题与页面重定向JavaScript

如何检查夏令时与时间在Javascript?