4
4
.
.
1
1
.
.
6
6
@
@
T
T
e
e
s
s
t
t
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use @Test Annotation to indicate that Method is Junit Test Method.
This is needed to distinguish Test Methods from
Helper Methods (Helper Methods are used/called by Test Methods)
Application Methods (if you are adding Test Methods to business Classes instead of having separate Test Classes)
That way when you select a Class to run Test Methods Java would know which Methods it needs to run.
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 (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.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.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() {
//PERFORM ACTION
String result = myController.hello();
//TEST RESULT
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>