文章目录
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.19.0</version>
<scope>test</scope>
</dependency>
System Rules
用于测试使用java.lang.System
的代码的JUnit规则集合。
涉及功能
System Rules的范围分为五个部分。
1. System.out, System.err and System.in
Command-line应用从command-line读取并写入command-line。 使用SystemErrRule
,SystemOutRule
和TextFromStandardInputStream
提供输入文本并验证输出。
应用有时会无意间写入System.out
或System.err
。 通过使用DisallowWriteToSystemOut
和DisallowWriteToSystemErr
确保不会发生这种情况。
2. System.exit
使用ExpectedSystemExit
规则来测试调用System.exit(…)
的代码。验证调用了System.exit(…)
,验证此调用的状态码或检查断言应用程序已终止。
3. System Properties
如果你的测试处理系统属性,要求你必须设置它们并在测试之后恢复它们。为此,请使用ClearSystemProperties
、ProvideSystemProperty
和RestoreSystemProperties
规则。
4. Environment Variables
如果你的测试需要设置一个环境变量,那么使用EnvironmentVariables
规则。
5. Security Managers
使用ProvideSecurityManager
规则为测试提供特定的安全管理器。 测试后将还原系统的安全管理器。
用法
建议:系统规则至少需要JUnit 4.9。
以下所有示例都使用@Rule
注解,但是规则也可以与@ClassRule
注解一起使用。
系统属性
清空属性
ClearSystemProperties
规则在测试之前删除属性,并在测试完成时恢复属性的原始值。
public class MyTest {
@Rule
public final ClearSystemProperties myPropertyIsCleared
= new ClearSystemProperties("MyProperty");
@Test
public void overrideProperty() {
assertNull(System.getProperty("MyProperty"));
}
}
提供属性
ProvideSystemProperty
规则为要测试的系统属性提供一个任意值。测试后恢复原始值。
多实例
public class MyTest {
@Rule
public final ProvideSystemProperty myPropertyHasMyValue
= new ProvideSystemProperty("MyProperty", "MyValue");
@Rule
public final ProvideSystemProperty otherPropertyIsMissing
= new ProvideSystemProperty("OtherProperty", null);
@Test
public void overrideProperty() {
assertEquals("MyValue", System.getProperty("MyProperty"));
assertNull(System.getProperty("OtherProperty"));
}
}
单一实例
你也可以使用规则的单一实例来达到同样的效果:
public class MyTest {
@Rule
public final ProvideSystemProperty properties
= new ProvideSystemProperty("MyProperty", "MyValue").and("OtherProperty", null);
@Test
public void overrideProperty() {
assertEquals("MyValue", System.getProperty("MyProperty"));
assertNull(System.getProperty("OtherProperty"));
}
}
属性文件
可以使用属性文件为ProvideSystemProperty
规则提供属性。文件可以来自文件系统或类路径。
在第一种情况下使用
@Rule
public final ProvideSystemProperty properties
= ProvideSystemProperty.fromFile("/home/myself/example.properties");
在第二种情况下使用
@Rule
public final ProvideSystemProperty properties
= ProvideSystemProperty.fromResource("example.properties");
恢复属性
当测试完成时,RestoreSystemProperties
规则取消所有系统属性的更改(无论它是否通过)。
public class MyTest {
@Rule
public final RestoreSystemProperties restoreSystemProperties
= new RestoreSystemProperties();
@Test
public void overrideProperty() {
//after the test the original value of "MyP