4
4
.
.
1
1
.
.
5
5
@
@
S
S
p
p
r
r
i
i
n
n
g
g
B
B
o
o
o
o
t
t
T
T
e
e
s
s
t
t
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use @SpringBootTest to create Spring Boot Context for testing.
This will instantiate Controller and other Beans making @Autowired work inside Application and @Test Methods.
Otherwise
@Autowired wouldn't work neither inside the Application nor in the Test Methods
therefore we would need to use Controller controller = new Controller() inside the @Test Method instead
and if inside Controller we have @Autowired Repository repository, repository will not get instantiated
Creating Spring Boot Context is time consuming operation but it is done only once (and not for every Test Method).
In other words Context gets cached between Test Methods remembering changes done by previous Test Methods.
Application Schema [Result]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
http://localhost:8080/Hello
Tomcat
hello()
MyController
MyControllerTest
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_test_controller.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";
}
}
MyControllerTest.java
package com.ivoronline.springboot_junit_test_controller.controllers;
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 {
@Autowired MyController myController;
@Test
void hello() {
String result = myController.hello();
assertEquals("Hello from Controller", result);
}
}
R
R
e
e
s
s
u
u
l
l
t
t
http://localhost:8080/Hello
Run Test Class: PersonTest
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>