Test Classes and Methods Requirement

Test Classes and Methods Requirement

JUnit 5 is the latest version of Junit. It has a brand new architecture and more capabilities compared to the previous generation of Junit. In this article, we will quickly go through some of the main features and concepts of JUnit 5. In this article we go over the high-level structural requirement for writing Unit Tests. Generally, we write test method to represent a test case or a certain scenario which we want to validate. Such test methods would reside inside a Class. With Junit5 we don't need to mark or annotate the main class with any special JUnit specific annotations. Junit5 will be able to

Test Class

Any top-level class, static member class, or @Nested class that contains at least one test method. We don't need to annotate the Class, JUnit5 will be able to find test methods defined inside it.
Class Requirement
The Class should contain only one Constructor and the Class should not be an abstract Class.

Test Method

Any not abstract instance method that is annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate.
Test Method
The test method should not return any value and should not be abstract.

Lifecycle Method

Any method that is directly annotated or meta-annotated with @BeforeAll, @AfterAll, @BeforeEach, or @AfterEach Lifecycle methods can be inherited from parent class. Lifecycle methods should not be private and should not return any value.
Lifecycle Method
Should not be private and should not return value. @BeforeAll and @AfterAll should be used on a static method


Following Example shows a Test Class with one test method annotated with @Test and four Lifecylcle emthods
package com.bootng.start;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;

public class SimpleHelloTest3 {

	public static void method1() {
		System.out.println("method 1");
	public void method2() {
		System.out.println("method 2");
	public static void method3() {
		System.out.println("method 3");
	public void method4() {
		System.out.println("method 4");
	public void test_hello() {
		String msg = "hello";
		assertEquals(msg, "hello", " message is equal Hello");

Running the above test would output the following. method1 and method2 would be executed before the actual test and then method4 and method3 would be executed.
Console Output
method 1 method 2 test_hello method 4 method 3

No comments :

Post a Comment

Please leave your message queries or suggetions.