Share
One-Page Tutorial for JUnit

One-Page Tutorial for JUnit

In this page, I’ll try to make the process of JUnit Test Suite learning as simple as possible: It’s one-chapter tutorial!

What is JUnit?

JUnit is a framework for implementing testing in Java. It provides a simple way to test specific areas of a Java program.

JUnit features include:

Assertions for testing expected results
Test fixtures for sharing common test data
Test suites for easily organizing and running tests
Graphical and textual test runners

Why Use JUnit?

Writing a JUnit Test cases is one of the best practice which every developer Should Opt. It gives a sense of confidence that whatever logic you are writing is correct, as it forces you to explicitly declare the expected results of specific program execution routes. When debugging it is possible to write a test which expresses the results you are trying to achieve and then debug until the test comes out positive

JUnit promotes the idea of first testing then coding, in that it is possible to setup test data for a unit which defines what the expected output is and then codes until the tests pass.

“Writing a few lines of code, then a test that Should run, or even better, to write a test that won’t run, then write the code that will make it run.”

JUnit Versions

The following versions of JUnit are available.

JUnit 3.8 uses specific naming conventions for identifying test classes, methods, and suites. Naming conventions are described below:

Test Case Class: Named [classname] Test.java, where classname is the name of the class that is being tested.
Test Case Method: Named test [methodname], where methodname is the name of the method that is tested.
Test Suite: Default name for Eclipse is AllTests.java

JUnit 4.x is a test framework which uses annotations to identify methods which are tested. All test methods can be executed in an arbitrary order. Therefore tests do not depend on other tests.

Test Case Class: Named [classname] Test.java, where classname is the name of the class that is being tested.
Test Case Method: Annotate the method with @Test. The method name does not have to start with test.
Test Suite: Only write a suite () method if you want to run your JUnit 4 tests with the JUnit 3.8 test runner.
Test Set Up: Annotate the method with @Before
Test Tear Down: Annotate the method with @After

Use a method provided by JUnit to check the expected result of the code execution versus the actual result

We can use Eclipse or the class “org.junit.runner.JUnitCore” to run the test.

JUnit Test Suite

If several test cases need to be executed, we can combine them into a test suite. Running a test suite will execute all tests in that suite in one go.

To create a test suite

Select your test classes

Junit

Right click on it → New → other

Junit

Select JUnit → JUnit Test Suite.

Junit

Select “Next” and select the methods for which you want to create a test.

Junit

Example of JUnit Test

Create a Java class in Eclipse.

Junit

Select the Java class created in Step1, and right mouse clicks and select New ->JUnit Test case.

Junit

Select “New JUnit 4 Test” and fill the remaining details.

Junit

Click “Next” and Select the methods which need to be tested. In the below screenshot, add(int, int) method is selected.

Junit

Click on “Finish” and a new class is opened through which the base class needs to be tested.

If compilation error is shown in the new class (Created in Step 5), please add Junit In the class path.

Write code in the test class

Junit

Click on “Run As à Junit Test” to run the code.

Junit

If the code runs successfully, the following screen would appear.

Junit

If Code doesn’t work as expected then it would show a red bar.

Junit

How to add JUnit in the classpath?

Please follow the steps mentioned below in order to pass JUnit in the classpath of the project.

Click on Project à Properties as shown in the screenshot.

Junit

Go to “Java Build Path” and Click on the “Add Library” button (as shown in screenshot).

Junit

Select “Junit” and click “Next”.

Junit

Select” Junit Java Version” as “JUnit4” and click on Finish button.

Junit

Click “Ok” to successfully add JUnit4 in the classpath.

Junit

Annotations Used in JUnit

Annotations provide more flexible initialization and cleanup, timeouts, and parameterized test cases.

The following table gives an overview of the available annotations in JUnit 4.x.

Annotation Description
@Test

public void method()

The annotation @Test identifies that a method is a test method.
@Before

public void method()

This will execute the method before each test method. This method can prepare the test environment (e.g. read input data, initialize the class).
@After

public void method()

This will execute the method after each test method. This method can clean up the test environment (e.g. deletes temporary data, restore defaults).
@BeforeClass

public void method()

This will execute the method once, before the start of all tests. This can be used to perform time intensive activities, for example, to connect to a database.
@BeforeClass

public void method()

Will execute the method once, before the start of all tests. This can be used to perform time intensive activities, for example, to connect to a database.
@AfterClass

public void method()

Will execute the method once after all tests have finished. This can be used to perform clean-up activities, for example, to disconnect from a database.
@Ignore Will ignore the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test

(expected = Exception.class)

Fails, if the method does not throw the named exception.
@Test(timeout=100) Fails if the method takes longer than 100 milliseconds.

Assert statements

The JUnit test case (method) Should have at least one assert statements, otherwise, it would be useless to pass the test without actually checking the value of any data.

If any assert statement fails, the test progress bar in the JUnit view will be red. Also, failing of assert statement will cease execution for that test case. Therefore, assert statements after that point will not be executed.

The most common assert statement is assertEquals() which take at least two arguments.

The first argument is the expected value of data and the second argument is the actual value of that data, which is obtained by a method call in the test case. The method will check for equality between the two pieces of data and show the result.

The following table gives an overview of the available assert statements.

Statement Description
fail(String) Used to check that a certain part of the code is not reached. Or to have failing test before the test code is implemented.
assertTrue(true) / assertTrue(false) Will always be true / false. Can be used to predefine a test result, if the test is not yet implemented.
assertTrue([message], boolean condition) Checks that the boolean condition is true.
assertsEquals([String message], expected, actual) Tests that two values are the same.

Note: for arrays the reference is checked not the content of the arrays.

assertsEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that the object is not null.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.

That’s it. Thank you for reading this post.

I want you to do something for me right now: Leave a comment !!!

Like this post? Don’t forget to share it!

Leave a Comment

*