System Rules 更好的测试

1:编写测试事例时候,我们要从控制台拿到数据与断言进行对比,通常要编写jdk 标准输出的屏蔽控制器.文章标题的包,能够更好的为我们进行工作.

package demo2;

import static org.junit.Assert.assertEquals;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;

public class demo1 {
	
	@Rule // 过去写法
	private final StandardOutputStreamLog log=new StandardOutputStreamLog();
	
	//正确输出
	@Rule 
	private final SystemOutRule sRule=new SystemOutRule();
	
	//错误输出
	@Rule
	private final SystemErrRule errrule=new SystemErrRule();
	
	@Test
	public void miantest() {
		sysou();
		assertEquals(2, sRule.getLog());
	}

	private void sysou() {
		System.out.println(2);
	}

}

其实使用事例介绍

Clear Properties

public class MyTest {
	@Rule
	public final ClearSystemProperties myPropertyIsCleared
	 = new ClearSystemProperties("MyProperty");

	@Test
	public void overrideProperty() {
		assertNull(System.getProperty("MyProperty"));
	}
}

Provide Properties

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"));
	}
}
原文地址:https://www.cnblogs.com/dgwblog/p/8094117.html