JUnit Overview


JUnit is one of the most popular unit testing framework which has significant role in test-driven development process. In JUnit tutorials we will understand and see examples of below topics.

  • JUnit annotations like @Test, @Before, @BeforeClass, @After, @AfterClass, etc…
  • JUnit assertions like assertEquals, assertTrue, assertFalse, etc…
  • Junit test execution order
  • Assertion and annotation examples
  • Junit suites
  • JUnit-2: Hamcrest Matchers
  • JUnit-3: Rules
  • JUnit-4: Categories
  • JUnit-5: Parametrized Tests


This tutorial is designed for the people who are dealing with unit tests, carrying out automation with Selenium Webdriver and want to have information about JUnit.


Development Kit: JAVA JDK
Java Test Runner: JUnit (http://junit.org/)
IDE: IntelliJ (I prefer IntelliJ) also you can go with Eclipse or Netbeans
Nice to have: Before starting this tutorial, it is nice to have basic knowledge of JAVA or any other object-oriented programming languages. Also, it is better to check “Quick Start to Selenium WebDriver with JAVA & JUnit & Maven & IntelliJ” tutorial before starting this one.

JUnit Naming Conventions

In general, test classes’s names should be ended with “Test” suffix. Also, it is highly recommended to give a meaningful name for your test classes such as FirefoxOrderCheckTest, ChromeLoginTest, etc… In this way, you can easily understand the functionalities of test classes.

Defining a Test in JUnit

To start a Junit test, you need to annotate a method with @Test annotation. There are many annotations in Junit and I will explain them in below section but the most critical annotation is “@Test” annotation. This indicates that the following method is a test method. In your test methods, you use “assert” statements to check the conditions that you are testing. It is a very good habit to write clear message in assert statements that helps us to understand the problems easily. I also explained them in Assertions section.

Most Common JUnit Annotations

JUnit comprises of some annotations that help us to run JUnit tests more easily and make them more readable. By using JUnit annotations, we can mark the methods as test methods and do various configurations on them. I listed frequently used annotations and their description in below table and you can find examples of all annotations in examples section.

Annotation Description
public void method()
The @Test annotation indicates the following method as a test method.

Following method has to declared as public void

public void method()
This method is executed before each test.

It is generally using for setting necessary preconditions.

Following method has to declared as public void

public void method()
This method is executed after each test.

It is used to delete temporary data, restore default settings.

Following method has to declared as public void

public static void method()
The following static method is executed once, before the start of all tests.

It is generally using for highly intensive operations such as DB connection.

Following method has to declared as public static void

public static void method()
The following static method is executed once, after all tests have been completed.

It is generally using for clean-up activities such as disconnect from a database.

Following method has to declared as public static void

public static void method()
This annotation is useful when you want temporarily disable the execution of a specific test.

Following method has to declared as public static void

@Test (expected = Exception.class) If the method does not throw the given exception, test will fail.
@Test(timeout=500) If the method takes longer than 500 milliseconds, test will fail.


 Junit’s assert class consists of several static methods to test specific conditions. Assert statements generally starts with assert keyword and then check specific conditions. You can specify meaningful error messages to understand what did go wrong after the test execution. General form of these methods is (“Error Message”, “Expected Value”, “Actual Value”). They compare expected value with actual value. If expected and actual values are not match then assert method throws “AssertionException” and you will see you error message output of IDE console. All assertions explanations are described in Junit website (http://junit.org/apidocs/org/junit/Assert.html). In this tutorial, I will go with the important ones and give examples of all of them in examples section.

  Assert Methods & Description & Syntax
1 void assertEquals (“Message”, boolean expected, boolean actual)

It compares that the given two values are same.

Syntax: assertEquals(“Str1 is not equal to str 2”, str1, str2);

2 void assertTrue(“Message”, boolean condition)
  It checks that the boolean condition is true.

Syntax: assertTrue(“Bolean expression is not TRUE! Please check it!”, val1 < val2);

3 void assertFalse(“Message”, boolean condition)
  It checks that the boolean condition is false.

Sytnax: assertTrue(“Bolean expression is not FALSE! Please check it!”, val1 < val2);

4 void assertNull(“Message”, Object object)
  It checks that the object is null

Sytnax: assertNotNull(“Object is not NULL! Pls check it!”, obj);

5 void assertNotNull(“Message”, Object object)
  It checks that the object is not null

Sytnax: assertNotNull(“Object is NULL! Pls check it!”, obj);

6 void assertSame(“Message”, boolean condition)
  It checks that two objects refer to the same object

Sytnax: assertSame(obj1,obj2);

7 void assertNotSame(boolean condition)
  It checks that two objects do not refer to the same object

Sytnax: assertNotSame(obj1,obj2);

Test execution order

Junit tests are running in an arbitrary order. If you want to run your tests in fixed order, you should use @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation. With this annotation you can lexically sort and test the methods in ascending order. It is shown in below image.

Annotation and Assertion Examples

1) Creating a Junit Package and Junit Test Classes

Creating a JAVA project is described in “Quick Start to Selenium WebDriver with JAVA & JUnit & Maven & IntelliJ” tutorial. Thus, I will not start from the beginning.

Right click “java” folder, then go to “New” and click “Package”.


Give a package name to combine all JUnit tests in that package as shown below.


For annotation and assertion examples, right click to “junitexamples” package and go to “New” then click “Java Class”.


Then, for annotation test, give a “JunitAnnotationTest” name to the class (java file).


For assertion examples, give a “JunitAssertionTest” name to the class (java file).


Finally, our project structure will look like below.


2) Annotation Example

When you run below code, you will see that

@BeforeClass runs only once before the all tests started

@Before runs before each test started

@Test defined attached method is a test method.

@After runs after each test finished

@AfterClass runs only once after the all test finished.

In below code I used “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation and lexically ordered test names to run the tests in lexical order.

I mean that all test names are started with T01_…, then T02_…, then T03…

By using “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation, these test cases will run in following order T01 → T02 → T03

~ In below code, I tried to explain important points with inline comments. ~

Output of Annotation Example:

3) Assertion Example

In below example, I wanted to show that all assertions that I explained in assertions section. You can find detailed information in comment lines. When you run below code all assertions will pass. Also, you can play with actual and expected values and will see what is going to happen according to your changes.

JUnit Test Suites

If you have more than one test classes, you can combine them into a test suite. If you run this test suite, test classes will be executed in specified order.

I used suites while I was automating www.teknosa.com multiple browsers login test cases. In the following example I added three login test classes into the test suite and run them altogether.

You can also see the project architecture below.



Now you have learned:

  • How to use JUnit annotations in your unit and selenium tests.
  • Meanings of JUnit assertions.
  • How to execute test in ascending and descending lexical order.
  • You saw some assertion and annotation examples.
  • How to use Junit suites


JUnit, unit testing, test framework[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]


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...
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...

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...

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...

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...

How to Write Smart XPath Locators

By Onur Baskirt / Sep 24, 2017 / 4 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...

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 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. Audience...
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...

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...

Selenium Webdriver Performance testing with Jmeter and Selenium Grid

By Ozgur Kaya / Aug 9, 2016 / 2 Comments
In this post, we will complete Selenium Webdriver Performance testing scenario using Jmeter and Selenium Grid. 1- Install Java 7 or later If necessary https://java.com/tr/download/ 2- Download latest Jmeter version 3.0 or higher. http://jmeter.apache.org/download_jmeter.cgi 3- Download Jmeter PluginsManager JAR file and...
By | 2017-01-13T21:33:47+00:00 September 4th, 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