【JAVA-UT】11、Runner--使用什么来运行你,我的UT

文|码术张

一、什么是Runner

下面这个UT,对您来说,现在应该是小菜一碟了。

public class ResultTest {
  @Test
  public void should_returnString() {
    // given
    String expectedString = "downLoadStatus: Fail, failureReason: cannot connect";
    Result result = new Result("Fail", "cannot connect");

    // when
    String realString = result.toString();

    // then
    Assert.assertEquals(expectedString, realString);
  }
}

given、when、then下的语句,各自描述了:
条件的设置;
执行被测功能;
结果是否符合期望的验证。

不过,这还不是全部。
在这个“家庭”里,还有一个特别重要的成员。
是谁呢?
Runner。

每一个测试类,都有一个Runner。
什么是Runner?
Runner是"编译器",也是"CPU"。

它是“编译器”,是因为Runner会做这两件事:
1,预处理。
判断语法是否规范。
比如@Test注释的方法,其返回值应当是void。
若违反了要求,将这“作品"退回作者,并附上评语。
如果合格,进入下一处理阶段。
2,“翻译”。
将测试类进行分解、排序。
分解为一个个执行单元,并排序。
这就好比将A语言的源程序翻译为B语言的等价程序。

它是"CPU",是因为Runner的有一个方法,
run方法
runner.run()
调用这个方法后,代码才开始进入运行阶段。
这就是为什么称它为runner的原因吧。

二、如何使用Runner

Junit提供了三种Runner:
BlockJUnit4ClassRunner
Suite
Parameterized
第3种不常用,所以这里不介绍。

1. BlockJUnit4ClassRunner的使用

BlockJUnit4ClassRunner是Junit4默认的runner。
使用方式1:
@RunWith(BlockJUnit4ClassRunner.class)
使用方式2:
BlockJUnit4ClassRunner.class的别名是JUnit4.class。
@RunWith(JUnit4.class)
使用方式3:
不使用RunWith语句。

开头的例子,使用了方式3。
分别用方式1、方式2改写如下:

@RunWith(BlockJUnit4ClassRunner.class)
public class ResultTest {
 ...
}
@RunWith(JUnit4.class)
public class ResultTest {
 ...
}
2. Suite的使用

Suite是将多个runner串联起来的一个runner。
如何使用Suite呢?

  1. 添加RunWith语句
    @RunWith(Suite.class)
  2. 添加SuiteClasses语句
    @SuiteClasses({Test1.class, Test2.class...})
    比如有两个测试类,分别测试ipv4、ipv6模式下的ping功能。
public class PingInIpv4modeTest {
  @Test
  public void printIpv4() {
    System.out.println("This is ipv4.");
  }
}
public class PingInIpv6modeTest {
  @Test
  public void printIpv6() {
    System.out.println("This is ipv6.");
  }
}

要将它们合并为一个整体,就需要用到Suite

@RunWith(Suite.class)
@Suite.SuiteClasses({
    PingInIpv4modeTest.class,
    PingInIpv6modeTest.class
})
public class PingTest {
    //nothing
}

当运行PingTest类时,就会运行SuiteClasses中所有的类。
如下图所示:


result.PNG

需要注意的是:
一个class声明为Suite后,其内部的方法已经无意义,也无法运行。
在上面的PingTest中,加入一个方法testInSuite,运行这个方法,会出现错误:

@RunWith(Suite.class)
@Suite.SuiteClasses({
    PingInIpv4modeTest.class,
    PingInIpv6modeTest.class
})
public class PingTest {
  @Test
  public void testInSuite() {
    System.out.println("it is testInSuite");
  }
}
result-of-running-method-in-suite.PNG
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • JUnit Intro Android基于JUnit Framework来书写测试代码。JUnit是基于Java语...
    chandarlee阅读 2,317评论 0 50
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,803评论 18 399
  • 不知不觉已进入生命的秋,再过几个月就四十七岁了,韶华易逝,光阴似箭。 回首来时路:,经历了多少曲折迷茫。家在城郊,...
    爱采菜菜菜阅读 152评论 0 0
  • 现在是一个微信号 就可以产生某种联系的时代 哪怕这种联系只是僵尸好友的存在 但我们都会颇为坚定地认为 “留着呗,说...
    唠叨的宝阅读 224评论 0 0