JUnit Annotations Tutorial with Example: What is @Test and @After (2023)

What is JUnit Annotations?

JUnit Annotations is a special form of syntactic meta-data that can be added to Java source code for better code readability and structure. Variables, parameters, packages, methods and classes can be annotated. Annotations were introduced in Junit4, which makes Java code more readable and simple. This is the big difference between Junit3 and Junit4 that Junit4 is annotation based.

With the knowledge of annotations in Junit5, one can easily learn and implement a JUnit test. Below is the important and frequently used JUnit annotations list:

S.No.AnnotationsDescription
1.@TestThis annotation is a replacement of org.junit.TestCase which indicates that public void method to which it is attached can be executed as a test Case.
2.@BeforeThis annotation is used if you want to execute some statement such as preconditions before each test case.
3.@BeforeClassThis annotation is used if you want to execute some statements before all the test cases for e.g. test connection must be executed before all the test cases.
4.@AfterThis annotation can be used if you want to execute some statements after each Test Case for e.g resetting variables, deleting temporary files ,variables, etc.
5.@AfterClassThis annotation can be used if you want to execute some statements after all test cases for e.g. Releasing resources after executing all test cases.
6.@IgnoresThis annotation can be used if you want to ignore some statements during test execution for e.g. disabling some test cases during test execution.
7.@Test(timeout=500)This annotation can be used if you want to set some timeout during test execution for e.g. if you are working under some SLA (Service level agreement), and tests need to be completed within some specified time.
8.@Test(expected=IllegalArgumentException.class)This annotation can be used if you want to handle some exception during test execution. For, e.g., if you want to check whether a particular method is throwing specified exception or not.

In this tutorial, you will learn-

  • JUnit Annotations Example
  • JUnit Assert Class
  • JUnit Test Cases Class
  • JUnit TestResult Class
  • JUnit Test Suite Class

JUnit Annotations Example

Let’s create a class covering important JUnit annotations with simple print statements and execute it with a test runner class:

Step 1) Consider below java class having various methods which are attached to above-listed annotations:

JunitAnnotationsExample.java

package guru99.junit;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertFalse;import java.util.ArrayList;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Ignore;import org.junit.Test;public class JunitAnnotationsExample { private ArrayList<String> list; @BeforeClass public static void m1() { System.out.println("Using @BeforeClass , executed before all test cases "); } @Before public void m2() { list = new ArrayList<String>(); System.out.println("Using @Before annotations ,executed before each test cases "); } @AfterClass public static void m3() { System.out.println("Using @AfterClass ,executed after all test cases"); } @After public void m4() { list.clear(); System.out.println("Using @After ,executed after each test cases"); } @Test public void m5() { list.add("test"); assertFalse(list.isEmpty()); assertEquals(1, list.size()); } @Ignore public void m6() { System.out.println("Using @Ignore , this execution is ignored"); } @Test(timeout = 10) public void m7() { System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case"); } @Test(expected = NoSuchMethodException.class) public void m8() { System.out.println("Using @Test(expected) ,it will check for specified exception during its execution"); }}

Step 2) let’s create a test runner class to execute above test:

TestRunner.java

package guru99.junit;import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner {public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitAnnotationsExample.class);for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println("Result=="+result.wasSuccessful()); }} 

Expected Result

  • All the test cases will be executed one by one, and all print statement can be seen on a console.
  • As discussed in above table @Before annotation in JUnit, @BeforeClass [ method m1() and m2() ] will be executed before each and before all test cases respectively.
  • In the same way @After in JUnit, @afterClass (method m3() and m4()) will be executed after each and after all test cases respectively. @ignore (method m6())will be treated as ignoring the test.

Let’s analyse test cases used in above java class in detail:

  1. Consider method m5() as given below :
@Test public void m5() { list.add("test"); assertFalse(list.isEmpty()); assertEquals(1, list.size()); }

In above method as you are adding a string in the variable “list” so

  • list.isEmpty() will return false.
  • assertFalse(list.isEmpty()) must return true.
  • As a result, the test case will pass.

As you have added only one string in the list, so the size is one.

  • list.size() must return int value as “1” .
  • So assertEquals(1, list.size()) must return true.
  • As a result, the test case will pass.
  1. Consider method m7() as given below :
@Test(timeout = 10) public void m7() { System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case"); }

As discussed above @Test(timeout = 10)annotation is used to enforce timeout in the test case.

  1. Consider method m8() as given below :
@Test(expected = NoSuchMethodException.class) public void m8() { System.out.println("Using @Test(expected) ,it will check for specified exception during its execution"); }

As discussed above @Test(expected) will check for specified exception during its execution so method m8() will throw “No Such Method Exception.” As a result, the test will be executed with an exception.

As all test cases are passed, this results in a successful test execution.

Actual Result

As there are three test cases in above example, all test cases will be executed one by one. See output below:

JUnit Annotations Tutorial with Example: What is @Test and @After (1)

JUnit Annotations Example

See below print statements which can be seen on console:

Using @BeforeClass , executed before all test cases

Using @Before annotations, executed before each test cases

Using @After, executed after each test cases

Using @Before annotations, executed before each test cases

Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case

Using @After, executed after each test cases

Using @Before annotations, executed before each test cases

Using @Test(expected) ,it will check for specified exception during its execution

Using @After, executed after each test cases

Using @AfterClass, executed after all test cases

JUnit Assert Class

This class provides a bunch of assertion methods useful in writing a test case. If all assert statements are passed, test results are successful. If any assert statement fails, test results are failed.

As you seen earlier, below table describes important Assert methods and description:

S.No.MethodDescription
1.void assertEquals(boolean expected, boolean actual)It checks whether two values are equals similar to equals method of Object class
2.void assertFalse(boolean condition)functionality is to check that a condition is false.
3.void assertNotNull(Object object)“assertNotNull” functionality is to check that an object is not null.
4.void assertNull(Object object)“assertNull” functionality is to check that an object is null.
5.void assertTrue(boolean condition)“assertTrue” functionality is to check that a condition is true.
6.void fail()If you want to throw any assertion error, you have fail() that always results in a fail verdict.
7.void assertSame([String message]“assertSame” functionality is to check that the two objects refer to the same object.
8.void assertNotSame([String message]“assertNotSame” functionality is to check that the two objects do not refer to the same object.

JUnit Test Cases Class

To run multiple test, TestCase class is available in org.junit.TestCase packages. @Test annotation tells JUnit that this public void method (Test Case here) to which it is attached can be run as a test case.

Below table shows some important methods available in org.junit.TestCase class:

S.No.MethodDescription
1.int countTestCases()This method is used to count how many number of test cases executed by run(TestResult tr) method.
2. TestResult createResult()This method is used to create a TestResult object.
3.String getName()This method returns a string which is nothing but a TestCase.
4.TestResult run()This method is used to execute a test which returns a TestResult object
5.void run(TestResult result)This method is used to execute a test having a TestResult object which doesn’t returns anything.
6.void setName(String name)This method is used to set a name of a TestCase.
7.void setUp()This method is used to write resource association code. e.g. Create a database connection.
8.void tearDown()This method is used to write resource release code. e.g. Release database connection after performing transaction operation.

JUnit TestResult Class

When you execute a test, it returns a result (in the form of TestResult object). This TestResult object can be used to analyse the resultant object. This test result can be either failure or successful.
See below table for important methods used in org.junit.TestResult class:

S.No.MethodDescription
1.void addError(Test test, Throwable t)This method is used if you require add an error to the test.
2.void addFailure(Test test, AssertionFailedError t)This method is used if you require add a failure to the list of failures.
3.void endTest(Test test)This method is used to notify that a test is performed(completed)
4.int errorCount()This method is used to get the error detected during test execution.
5.Enumeration<TestFailure> errors()This method simply returns a collection (Enumeration here) of errors.
6.int failureCount()This method is used to get the count of errors detected during test execution.
7.void run(TestCase test)This method is used to execute a test case.
8.int runCount()This method simply counts the executed test.
9.void startTest(Test test)This method is used to notify that a test is started.
10.void stop()This method is used to test run to be stopped.

JUnit Test Suite Class

If you want to execute multiple tests in a specified order, it can be done by combining all the tests in one place. This place is called as the test suites.

See below table for important methods used in org.junit.TestSuite class:

S.No.MethodDescription
1.void addTest(Test test)This method is used if you want to add a test to the suite.
2.void addTestSuite(Class<? extends TestCase> testClass)This method is used if you want to specify the class while adding a test to the suite.
3.int countTestCases()This method is used if you want to count the number of test cases.
4.String getName()This method is used to get the name of the test suite.
5.void run(TestResult result)This method is used to execute a test and collect test result in TestResult object.
6.void setName(String name)This method is used to set the name of TestSuite.
7.Test testAt(int index)This method is used if you want to return the test at given index.
8.int testCount()This method is used if you want to return a number of tests in the Suite.
9.static Test warning(String message)This method returns a test which will fail and log a warning message.

Summary:

  • JUnit provides a portable API, which provides all important classes and Selenium annotations useful in writing a unit test.
  • Classes which are very useful while writing a test case
    • org.junit.Assert
    • org.junit.TestCase
    • org.junit.TestResult
    • org.junit.TestSuite
  • Important and frequently used JUnit annotations list@Before@BeforeClass@After

    @AfterClass

    @Test

    @Ignore

You Might Like:

  • JUnit Tutorial for Beginners: Learn in 3 Days
  • How to Download and Install JUnit in Eclipse
  • JUnit Test Cases @Before @BeforeClass Annotation
  • Create JUnit Test Suite with Example: @RunWith @SuiteClasses

FAQs

What is the use of @before and @after annotations in JUnit? ›

Exploring JUnit @Before and @After Annotations

The @Before annotation is used to define a method that should be executed prior to each test method, while the @After annotation specifies a method that should be run after each test method.

What is the use of @after in JUnit? ›

org.junit

Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.

What is the use of @test annotation in JUnit? ›

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.

What is the purpose of the @AfterClass annotation in JUnit? ›

Annotating a public static void method with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass methods are guaranteed to run even if a BeforeClass method throws an exception.

What is the use of @test annotation? ›

In any automation script, @Test annotation is the important part, where we write code/business logic. If something needs to be automated, that particular code needs to be inserted into the test method. The test method then executes @Test by passing attributes.

What runs exactly before and after @test annotation? ›

The @BeforeTest annotated method will be executed before the execution of all the test methods of available classes belonging to that folder. The @AfterTest annotated method will be executed after the execution of all the test methods of available classes belonging to that folder.

What is the purpose of the @after all annotation in junit5? ›

@AfterAll: This annotation causes the annotated method to be executed only after all tests have been completed. @Tag: This annotation can be used to declare tags that will be used to filter tests at the class or method level. @Disabled: This annotation is used at the class or method level to disable or skip tests.

What does @test mean in java? ›

3.3 JUnit 4's Annotations
AnnotationDescription
@TestThe annotated method is to be run as a test method.
@BeforeThe annotated method is to be run before EACH of the test method.
@AfterThe annotated method is to be run after EACH of the test method.
4 more rows

What is the @test annotation in JUnit 4? ›

The Junit 4. x framework is annotation based, so let's see the annotations that can be used while writing the test cases. @Test annotation specifies that method is the test method. @Test(timeout=1000) annotation specifies that method will be failed if it takes longer than 1000 milliseconds (1 second).

What are the basic annotations of JUnit? ›

The three basic JUnit annotations that are commonly used to write test methods: @Test, @Before and @After. By using these annotations, JUnit makes it easy to write and execute test methods in a consistent and repeatable way.

What is annotation after all tests in JUnit? ›

Annotation Type AfterAll

@AfterAll is used to signal that the annotated method should be executed after all tests in the current test class. In contrast to @AfterEach methods, @AfterAll methods are only executed once for a given test class.

What is before annotation in JUnit? ›

The @Before annotation is used when different test cases share the same logic. The method with the @Before annotation always runs before the execution of each test case. This annotation is commonly used to develop necessary preconditions for each @Test method.

What is before and after annotation in Java? ›

@BeforeClass and @AfterClass

The annotated method @BeforeClass will execute only once before the first test method is invoked in that class. The @AfterClass annotation will be executed only once after all the test methods are invoked in that class.

What is the use of @before and @after? ›

Before and "after" are used to show what happened 1st and what happened 2nd. They are subordinating conjunctions, but that is not very important. Let's look at the sentence patterns. "Before" and "after" can go at the beginning of a sentence or in the middle of a sentence.

What is the difference between AfterEach and BeforeEach in JUnit? ›

@BeforeEach - Use to run a common code before( eg setUp) each test method execution. analogous to JUnit 4's @Before. @AfterEach - Use to run a common code after( eg tearDown) each test method execution.

References

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated: 24/11/2023

Views: 6336

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.