JUnit Listeners

If you want to do some operations when your tests are started, passed, finished, failed, or skipped/ignored, you can use Listeners. Both JUnit and TestNG provide us Listeners, and in this article, I will explain how to add JUnit Listeners in your automation framework.

Listeners listen and handle events while your automation code is running. We can add a listener by creating a custom Runner. Then, we can use this custom runner in our test class with @RunWith annotation.

First, let’s write our Listener class by extending JUnit’s RunListener class and overriding its methods. I called our listener class as MyExecutionListener.

MyExecutionListener.java

MyExecutionListener

 

package junitexamples.listener;

/**
* Created by ONUR BASKIRT on 27.03.2016.
*/ import org.junit.Ignore;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener; import java.util.Date; public class MyExecutionListener extends RunListener { //Start and End time of the tests
long startTime;
long endTime; @Override
public void testRunStarted(Description description) throws Exception {
//Start time of the tests
startTime = new Date().getTime();
//Print the number of tests before the all tests execution.
System.out.println("Tests started! Number of Test case: " + description.testCount() + "\n");
} @Override
public void testRunFinished(Result result) throws Exception {
//End time of the tests
endTime = new Date().getTime();
//Print the below lines when all tests are finished.
System.out.println("Tests finished! Number of test case: " + result.getRunCount());
long elapsedSeconds = (endTime-startTime)/1000;
System.out.println("Elapsed time of tests execution: " + elapsedSeconds +" seconds");
} @Override
public void testStarted(Description description) throws Exception {
//Write the test name when it is started.
System.out.println(description.getMethodName() + " test is starting...");
} @Override
public void testFinished(Description description) throws Exception {
//Write the test name when it is finished.
System.out.println(description.getMethodName() + " test is finished...\n");
} @Override
public void testFailure(Failure failure) throws Exception {
//Write the test name when it is failed.
System.out.println(failure.getDescription().getMethodName() + " test FAILED!!!");
} //O.B: IntelliJ ignored by default. I did not succeed to run this method.
//If you know any way to accomplish this, please write a comment.
@Override
public void testIgnored(Description description) throws Exception {
super.testIgnored(description);
Ignore ignore = description.getAnnotation(Ignore.class);
String ignoreMessage = String.format(
"@Ignore test method '%s()': '%s'",
description.getMethodName(), ignore.value());
System.out.println(ignoreMessage + "\n");
}
}
 
 

Java

 
 

Second, we need to add the listener to the test execution. We can add the listener by calling the RunNotifier.addListener() method. This will register our JUnit Listener. I faced with a problem when I tried to use RunListener class’s testRunStarted method. Then, I found a solution that triggers this method after registering the listener in the run method. I wrote a comment about this solution in below code.

MyTestRunner.java

MyTestRunner
package junitexamples.listener;

/**
* Created by ONUR BASKIRT on 27.03.2016.
*/ import org.junit.AssumptionViolatedException;
import org.junit.internal.runners.model.EachTestNotifier;
import org.junit.runner.notification.RunNotifier;
import org.junit.runner.notification.StoppedByUserException;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement; public class MyTestRunner extends BlockJUnit4ClassRunner { public MyTestRunner(Class<?> klass) throws InitializationError {
super(klass);
} @Override
public void run (RunNotifier notifier){
System.out.println("Executing run()");
//Add Listener. This will register our JUnit Listener.
notifier.addListener(new MyExecutionListener()); //Get each test notifier
EachTestNotifier testNotifier = new EachTestNotifier(notifier,
getDescription());
try {
//In order capture testRunStarted method
//at the very beginning of the test run, we will add below code.
//Invoke here the run testRunStarted() method
notifier.fireTestRunStarted(getDescription());
Statement statement = classBlock(notifier);
statement.evaluate();
} catch (AssumptionViolatedException e) {
testNotifier.fireTestIgnored();
} catch (StoppedByUserException e) {
throw e;
} catch (Throwable e) {
testNotifier.addFailure(e);
}
}
}
 
 
 

Java

 
 

Third, we need to write a test to verify our listener’s functionality. We register our custom runner with @RunWith(MyTestRunner.class) annotation and for alphabetic test execution, we add @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation.

Extra: Also, you can combine listeners with custom Retry Rule which described in other JUnit article. Thus, when your test fails, it will rerun the failed test according to given retry count.

ListenerExampleTest.java

ListenerExampleTest

package junitexamples.listener;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; /**
* Created by ONUR on 27.03.2016.
*/
@RunWith(MyTestRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ListenerExampleTest { static WebDriver driver;
final private static String URL = "http://www.swtestacademy.com"; @BeforeClass
public static void setupTest(){
driver = new HtmlUnitDriver();
driver.get(URL);
} /*
//If you want, you can add Retry Rule. (I explained it in another post.)
//Thus, when your test fails, it will rerun by given retry count.
@Rule
public RetryRule retryRule = new RetryRule(3);
*/ @Test
public void T01_PassTest() {
//Check title
assertThat(driver.getTitle(), is("Software Test Academy"));
} @Test
public void T02_FailTest() {
//Check title
assertEquals("Title is wrong!!!", "WRONG TITLE", driver.getTitle());
} //IntelliJ ignored by default
@Ignore
public void T03_IgnoreTest() {
//Check title is correct
assertThat(driver.getTitle(), is("Software Test Academy"));
} //Throw Exception
@Test
public void T04_ExceptionTest() {
throw new RuntimeException();
}
}
 
 
 
 

Java

 

Result:

How to use Junit Listener的更多相关文章

  1. WebDriver - 添加失败截图

    WebDriver失败截图可以通过两种方式实现: 1. Use WebdriverEventListener 第一步:创建自己的WebDriverEventListener 创建自己的WebDrive ...

  2. 使用RunWith注解改变JUnit的默认执行类,并实现自已的Listener

    使用RunWith注解改变JUnit的默认执行类,并实现自已的Listener在平时的单元测试,如果不使用RunWith注解,那么JUnit将会采用默认的执行类Suite执行,如下类: public  ...

  3. Junit : how to add listener, and how to extends RunListener to override behaviors while failed

    http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html org.junit.runner ...

  4. [Java] Spring + SpringMVC + Maven + JUnit 搭建

    示例项目下载: https://github.com/yangyxd/SpringDemo 利用前面 SpringMVC 项目的配置方式,完成初步的项目创建.下面只讲一些不同之处. 传送门: [Jav ...

  5. How to Use JUnit With JMeter

    Do you need to use JUnit in your testing processes? To answer this question, let's take a look first ...

  6. 监听器Listener

    监听器 6个事件类,均以event结尾 *某些操作,如启动/关闭容器,创建/销毁会话,都将触发一种事件发生,当发生了某种事件,容器将创建对应的事件类对象 8个监听接口,均以Listener结尾 监听器 ...

  7. maven+springMVC+mybatis+junit详细搭建过程 ***

    springMVC+mybatis框架搭建 在上一遍博客中以及讲诉了新建maven项目的流程,现在紧跟上一遍文章,接着搭建spring项目 首先我们先要弄清搭建项目的一般流程,需要注意哪些方面,想要什 ...

  8. 使用JUnit单元测试入门

    一.JUnit是什么? JUnit是一个开发源代码的java测试框架,用于编写和运行可重复的测试.它是用于单元测试框架体系xUnit的一个实例(用于java语言).JUnit最初是由Erich Gam ...

  9. 获取JUnit的执行结果

    junit执行之后会有一个结果展示,下面就来看一下怎么获取这些结果并将其存储为一个对象 junit代码如下: package test; import org.junit.After; import ...

随机推荐

  1. sqli-labs(四)

    第七关: 输入?id=1 页面显示如下,可以看出这关大概是锻炼利用sql来写入一句话木马. 这里说我下我的探测流程(主要是为了知道后台的sql是怎样拼凑的): 输入?id=1' 报错  说明后台是用的 ...

  2. java 3大特性

    1. 封装 : 定义: 封装是把过程和数据包围起来,对数据的访问只能通过已定义的接口. 作用: 封装通过对属性增加修饰符来控制数据的访问权限,定义数据的访问接口,增加了数据的隐秘性和安全性. 2.继承 ...

  3. html5-css渐变色

    div{    width: 300px;    height: 100px;    margin: 50px;    padding: 50px;    border:5px groove rgba ...

  4. codefroces 266

    D题说的是 你选定一个区间如[l r] 将这个区间内的每个数都加上1,然后求将这整个整个序列都变成h的方案数有多少种 没有一个位置会有超过1次方[  或者放 ] 考虑当前位置放的是什么 有5种 - 不 ...

  5. 20155228 2016-2017-2 《Java程序设计》第2周学习总结

    20155228 2006-2007-2 <Java程序设计>第2周学习总结 教材学习内容总结 类型 Java可以区分为基本类型和类类型(或称参考类型).对于基本类型,使用时得考虑一下数据 ...

  6. 【Hadoop学习之六】MapReduce原理

    一.概念MapReduce:"相同"的key为一组,调用一次reduce方法,方法内迭代这一组数据进行计算 块.分片.map.reduce.分组.分区之间对应关系block > ...

  7. 开源词袋模型DBow3原理&源码(二)ORB特征的保存和读取

    util里提供了create_voc_step0用于批量生成features并保存,create_voc_step1读入features再生成聚类中心,比较适合大量语料库聚类中心的生成. 提取一张图的 ...

  8. 转:异常处理之ThreadException、unhandledException及多线程异常处理

    转载自:http://www.cnblogs.com/levin9/articles/2319251.html 一:ThreadException和unhandledException的区别 处理未捕 ...

  9. go语言,golang学习笔记1 官网下载安装,中文社区,开发工具LiteIDE

    go语言,golang学习笔记1 官网下载安装,中文社区,开发工具LiteIDE Go语言是谷歌2009发布的专门针对多处理器系统应用程序的编程进行了优化,使用Go编译的程序可以媲美C或C++代码的速 ...

  10. [转载]Oracle PL/SQL之LOOP循环控制语句

    在PL/SQL中可以使用LOOP语句对数据进行循环处理,利用该语句可以循环执行指定的语句序列.常用的LOOP循环语句包含3种形式:基本的LOOP.WHILE...LOOP和FOR...LOOP. LO ...