4
4
.
.
1
1
.
.
9
9
a
a
s
s
s
s
e
e
r
r
t
t
.
.
.
.
.
.
(
(
)
)
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use different assert() Methods which are used to assert/evaluate/compare provided values.
If values are don't match then Test ends in Failure at the first assert that didn't pass.
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 (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";
}
}
http://localhost:8080/Hello
Tomcat
hello()
MyController
MyControllerTest
MyControllerTest.java
package com.ivoronline.springboot_junit_assert.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;
//================================================================
// HELLO
//================================================================
@Test
void hello() {
//PERFORM ACTION
String result = myController.hello();
//TEST RESULT
assertEquals("Hello from Controller", result);
}
//================================================================
// ASSERTS PASS
//================================================================
@Test
void assertsPass() {
System.out.println("Inside testPass()");
assertEquals (5, 5);
assertNotEquals(5, 4);
assertTrue (true);
assertFalse (false);
assertNull (null);
assertNotNull (1);
}
//================================================================
// ASSERTS FAIL
//================================================================
@Test
public void assertsFail() {
System.out.println("Inside testFail()");
Integer i = 1;
assertEquals (5, 4); //java.lang.AssertionError: expected:<5> but was:<4>
assertNotEquals(5, 5); //java.lang.AssertionError: Values should be different. Actual: 5
assertTrue (false); //java.lang.AssertionError:
assertFalse (true); //java.lang.AssertionError:
assertNull (i); //java.lang.AssertionError: expected null, but was:<1>
}
}
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>