Outline

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

Audience

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.

Prerequisites

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
@Test
public void method()
The @Test annotation indicates the following method as a test method.

Following method has to declared as public void

@Before
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

@After
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

@BeforeClass
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

@AfterClass
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

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

Assertions

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

junit_2

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

junit_3

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

junit_4

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

junit_5

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

junit_6

Finally, our project structure will look like below.

junit_7

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.

junit_8

Summary

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

Keywords

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