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"));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,914评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,948评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,764评论 18 399
  • 小编费力收集:给你想要的面试集合 1.C++或Java中的异常处理机制的简单原理和应用。 当JAVA程序违反了JA...
    八爷君阅读 4,656评论 1 114
  • 女儿初中期间,为了上学往返方便,就开始了学区房租赁生活。租房子最大的问题,是如果房东房子自己有用,我们就要不定期搬...
    繁花坞阅读 966评论 8 23