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
Example
Following Example shows a Test Class with one test method annotated with @Test and four Lifecylcle emthods
SimpleHelloTest3
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 {
@BeforeAll
public static void method1() {
System.out.println("method 1");
}
@BeforeEach
public void method2() {
System.out.println("method 2");
}
@AfterAll
public static void method3() {
System.out.println("method 3");
}
@AfterEach
public void method4() {
System.out.println("method 4");
}
@Test
public void test_hello() {
String msg = "hello";
assertEquals(msg, "hello", " message is equal Hello");
System.out.println("");
}
}
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.
Note: Only a member of this blog may post a comment.