4
4
.
.
1
1
.
.
8
8
@
@
B
B
e
e
f
f
o
o
r
r
e
e
A
A
l
l
l
l
,
,
@
@
A
A
f
f
t
t
e
e
r
r
A
A
l
l
l
l
,
,
@
@
B
B
e
e
f
f
o
o
r
r
e
e
E
E
a
a
c
c
h
h
,
,
@
@
A
A
f
f
t
t
e
e
r
r
E
E
a
a
c
c
h
h
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use @Disable Annotation to skip specific Test Methods which is useful when you
want to concentrate on other Test Methods (and don't want to wait for disabled Test Methods to execute)
know that Test Method would fail because it is testing functionality that is still under development or being debugged
In this example we will create two Test Methods to test each Controller's Endpoint.
But one Test Method will be @Disable and therefore will not get executed.
Application Schema [Result]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_junit_test_controller (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside controllers package)
Create Test Class: MyControllerTest.java
MyController.java
package com.ivoronline.springboot_junit_beforeafter.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
return "Hello from Controller";
}
}
http://localhost:8080/Hello
Tomcat
hello()
MyController
MyControllerTest
MyControllerTest.java
package com.ivoronline.springboot_junit_beforeafter.controllers;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class MyControllerTest {
static int i;
@Autowired MyController myController;
@BeforeAll
public static void callBeforeAllTests() {
i = 100;
System.out.println("callBeforeAllTests() " + i);
}
@BeforeEach
public void callBeforeEachTest() {
i = i + 20;
System.out.println("callBeforeEachTest() " + i);
}
@Test
void hello() {
i = i + 3;
System.out.println("Test Method: hello() " + i);
String result = myController.hello();
assertEquals("Hello from Controller", result);
}
@AfterEach
public void callAfterEachTest() {
i = i - 20;
System.out.println("callAfterEachTest() " + i);
}
@AfterAll
public static void callAfterAllTests() {
i = i - 100;
System.out.println("\ncallAfterAllTests() " + i);
}
}