JUnit Rules


JUnit rules allow you to write code to do some before and after work. Thus, you don’t repeat to write the same code in various test classes. They are very useful to add more functionalities to all test methods in a test class. You can extend or reuse provided rules or write your own custom rules. The base rules are listed below and you can find details about them on https://github.com/junit-team/junit/wiki/Rules web page.

  • TemporaryFolder Rule
  • ExternalResource Rules
  • ErrorCollector Rule
  • Verifier Rule
  • TestWatchman/TestWatcher Rules
  • TestName Rule
  • Timeout Rule
  • ExpectedException Rules
  • ClassRule
  • RuleChain
  • Custom Rules

In Junit github link you can find all details of each rule. Also, their core mechanism and flow are described in this article very well. I want to demonstrate usage of some rules with examples.

Temporary Folder

The TemporaryFolder Rule allows you to create files and folders. These files are folders are deleted whether the test passes or fails when the test method finishes. By default, no exception is thrown if resources cannot be deleted. So, if you need to run a test that needs a temporary file or folder then you can use this rule as shown below.

Timeout Rule

The Timeout Rule applies the same timeout to all test methods in a class.

ExpectedException Rules

The ExpectedException Rule allows having more control on of expected exception types and messages.

Error Collector Rule

The ErrorCollector Rule allows execution of a test to continue after the first problem is found. It collects all the errors and reports them all at once.

Output:

Verifier Rule

 Verifier rule does a verification check and if it is failed, the test is finished with failing result. You can write your custom verification logic with Verifier Rule.

Output:

verifier_rule

TestWatchman/TestWatcher Rules

TestWatcher (and the deprecated TestWatchman) are classes for Rules and they watch test methods and write log for the each passing and failing tests. You can keep an eye on the tests with TestWatcher Rule.

Output:

TestName Rule

 The TestName Rule allows you to get current test name inside the test method.

ExternalResources & Class Rule

ExternalResource is a base class for Rules (like TemporaryFolder) that establishes an external resource before a test (a file, socket, server, database connection, etc.), and guarantee to tear it down afterward. This rule is more useful for integration tests.

With ClassRule annotation we can extend ExternalResource operation to multiple classes. It is very useful for when we need to repeat test setup/teardown for multiple classes. For example, if we are doing an integration test and we have to start the server before the test and stop it after the test, we should use ClassRule annotation. ClassRule must annotate public static field.

MyServer.java

ServerTest.java

TestFirstServer.java

TestSecondServer.java

RuleChain Rule

With JUnit 4.10, we can order several rules according to our needs using RuleChain rule.

LoggingRule.java

RuleChainTest.java

Output:

Custom Rules

In order to write your custom rule, we need to implement the TestRule interface. This interface’s only method that called apply(Statement, Description) returns an instance of Statement. The statement represents our tests within the Junit runtime and Statement#Evaluate() executes them. The description describes the individual test.

“The power from implementing TestRule comes from using a combination of custom constructors, adding methods to the class for use in tests, and wrapping the provided Statement in a new Statement.” (https://github.com/junit-team/junit/wiki/Rules)

Custom Rules can be written simply as follows:

We can use them in our tests by using @Rule annotation

Output:

I also want to give a real-life example. The following example is taking a screenshot when our web automation test fails. In below example, webdriver cannot find specified id and throws an exception, then it will be caught in evaluate() function’s catch block and it takes a screenshot.

ScreenShotRule.java

ScreenshotRuleTest.java

Summary

  • You learned how to use and the meanings of JUnit Rules.
  • You practiced with examples of  JUnit Rules.

Keywords

JUnit rules, unit testing, test framework

javafx

Database Operations in JavaFX

By Onur Baskirt / Apr 1, 2016 / 56 Comments
Before started this section, please check the first article and learn How to Start JAVAFX! http://www.swtestacademy.com/getting-started-with-javafx/ At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an...
extentreports

How to Write Smart XPath Locators

By Onur Baskirt / Sep 24, 2017 / 5 Comments
Hi all, in this tutorial, I will describe you how to write smart and non-brittle XPath locators. When we write our test scripts, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not...
extentreports

How to Write Effective CSS Locators

By Onur Baskirt / Oct 1, 2017 / 0 Comments
Hi all, in this tutorial, I will describe you how to write effective CSS locators to interrogate web elements for your automation projects. As a rule of thumb, your interrogation strategy should be in below order: First try to use...
rest assured

REST API Testing with Rest Assured

By Onur Baskirt / Mar 8, 2016 / 32 Comments
Outline In this post, I will explain what is API and API testing, what is the difference between SOAP and REST services, and how to test REST APIs with Rest Assured Library. What is API? API stands for Application Programming...
javafx

Getting Started with JavaFX

By Onur Baskirt / Mar 25, 2016 / 0 Comments
When I started to work in my current position, one of my task is to do manual operations for campaign products  every week. After the second week, I thought that I have to automate this task using a GUI based...
extentreports

Selenium-1: Quick Start to Automation with Selenium WebDriver & JAVA & JUnit & Maven & IntelliJ

By Onur Baskirt / Sep 8, 2015 / 26 Comments
Outline Selenium Webdriver is the most popular open source web test automation framework across the wide range of browsers and platforms. In this tutorial, you will learn how to do web test automation with Selenium Webdriver and the related tools....
extentreports

Selenium-11: Execute JavaScript with JavascriptExecutor

By Onur Baskirt / Jan 27, 2016 / 15 Comments
Outline Sometimes we cannot handle some conditions or problems with Webdriver, web controls don't react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change...
page object model

Page Object Model with C#

By Ege Aksoz / Jun 18, 2017 / 8 Comments
In the previous tutorial, we’ve taken the initial steps and entered the world of automated testing. We also wrote our first automated test. From this point on, since we are not just going to write one test, we need to...
extentreports

How to Select a Date From DatePicker Using Selenium

By Onur Baskirt / Aug 13, 2016 / 6 Comments
When you need to automate a airway, hotel, or similar websites you need to deal with Datepickers and some times it is a little bit cumbersome to select a specific date on the Datepicker or calendar.  In this post, I...

Getting Started with RobotFramework on Windows

By Onur Baskirt / Apr 25, 2016 / 12 Comments
What is RobotFramework? RobotFramework is a GENERIC test automation framework for acceptance testing and acceptance test-driven development (ATTD). What it means that you can do web, mobile, desktop and other test automation activities with related test libraries. These libraries can...
By | 2017-10-22T03:08:53+00:00 November 24th, 2015|JUnit, Test Frameworks, Unit Testing|0 Comments

About the Author:

Onur Baskirt
Onur Baskirt is a senior IT professional with 10+ years of experience. He worked at Bahçesehir University, ST Microelectronics, Huawei and Ericsson as research assistant, design verification engineer and software test leader. Also, he worked as software test leader and software operations manager at Turkey's biggest technology retailer, Teknosa. Now, he is working as Head of Software Testing and Manager of two Development Teams at Kariyer.net. His current research areas are technical software testing, programming, and computer science. Formerly, he has several research works and papers on digital chip design & verification. His hobbies are sport, dancing, traveling, and nutrition. You can find detailed information about him on his linked-in page.

Leave A Comment