JUnit Document
JUnit Document
RAGHU
JUnit is a popular unit-testing framework in the Java ecosystem. JUnit 5 added many new
features based on the Java 8 version of the language.
JUnit Platform
JUnit Jupiter
Blend of new programming model for writing tests and extension model for extensions
Addition of new annotations like @BeforeEach, @AfterEach, @AfterAll, @BeforeAll etc.
JUnit Vintage
Provides support to execute previous JUnit version 3 and 4 tests on this new platform
To implement JUnit5 based test cases in a project, add the following dependency to the
pom.xml file of the project:
JUnit 5 Library
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
</dependency>
Page 1 of 18
Mr. RAGHU
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.5.1</version>
</dependency>
JUnit Annotations
Annotation Description .
@DisplayName Declares a custom display name for the test class or test method
@BeforeEach Denotes that the annotated method should be executed before each test method
@AfterEach Denotes that the annotated method should be executed after each test method
@BeforeAll Denotes that the annotated method should be executed before all test methods
@AfterAll Denotes that the annotated method should be executed after all test methods
JUnit Assertions
Every test method must be evaluated against condition to true using assertions so that the test can
continue to execute. JUnit Jupiter assertions are kept in the org.junit.jupiter.api.Assertions class. All of
the methods are static.
Assertion Description .
Page 2 of 18
Mr. RAGHU
assertAll() Group many assertions and every assertion is executed even if one
or more of them fails
@Test
void testAssertEqual() {
assertEquals("ABC", "ABC");
assertEquals(20, 20, "optional assertion message");
assertEquals(2 + 2, 4);
}
@Test
void testAssertFalse() {
assertFalse("FirstName".length() == 10);
assertFalse(10 > 20, "assertion message");
}
@Test
void testAssertNull() {
String str1 = null;
String str2 = "abc";
assertNull(str1);
assertNotNull(str2);
}
@Test
void testAssertAll() {
String str1 = "abc";
String str2 = "pqr";
String str3 = "xyz";
assertAll("strings",
() -> assertEquals(str1,"abc"),
() -> assertEquals(str2,"pqr"),
() -> assertEquals(str3,"xyz")
);
@Test
void testAssertTrue() {
Page 3 of 18
Mr. RAGHU
assertTrue("FirstName".startsWith("F"));
assertEquals("Illegal Argument Exception occured", exception.getMessage());
}
pom.xml:-
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
Page 4 of 18
Mr. RAGHU
<version>4.5.1</version>
</dependency>
</dependencies>
SERVICE CLASS: -
package com.app.raghu;
TEST CLASS: -
package com.app.raghu;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(value = MethodOrderer.OrderAnnotation.class)
public class CalculatorTest {
Calculator calculator;
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
@DisplayName("Test Multiplication ")
@Order(20)
void testMultiply() {
Page 5 of 18
Mr. RAGHU
@Test
@Order(10)
//@Disabled
void testZero() {
assertNotEquals(100, calculator.multiply(4, 0),
"Regular multiplication should work");
}
@AfterEach
void clean() {
calculator = null;
}
}
SERVICE CLASS: -
package com.app.raghu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
static {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bootdb",
"root", "root");
} catch (SQLException e) {
e.printStackTrace();
Page 6 of 18
Mr. RAGHU
}
}
TEST CLASS: -
package com.app.raghu;
import java.sql.Connection;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@BeforeEach
public void setup() {
con1 = ConnectionUtil.getConnection();
con2 = ConnectionUtil.getConnection();
}
@Test
public void testNotNull() {
assertAll("Connections",
()->assertNotNull(con1),
()->assertNotNull(con2)
);
}
@Test
public void testSameRef() {
assertSame(con2, con1);
}
Page 7 of 18
Mr. RAGHU
@AfterEach
public void clean() {
con1 = con2 = null;
}
}
MOCKITO
Mockito is a java based mocking framework, used in conjunction with other testing frameworks
such as JUnit. It internally uses Java Reflection API and allows to create objects of a service. A mock
object returns a dummy data and avoids external dependencies.
What is Mocking?
It is a process of Creating a Dummy Implementation for dependent code.
What is Mocking?
Mocking is a way to test the functionality of a class in isolation.
Mocking does not require a database connection or properties file read or file server read to test
a functionality.
Mock objects do the mocking of the real service. A mock object returns a dummy data
corresponding to some dummy input passed to it.
Page 8 of 18
Mr. RAGHU
Exception support: It supports the exception. In Mockito, the stack trace is used to find the cause of the
exception.
Annotation support: It creates mock objects using annotations like @Mock.
Order support: It provides a check on the order of the method calls.
EXAMPLE#1
Service Code:
package com.app.raghu;
import org.junit.jupiter.api.Test;
System.out.println(p.getCode("Hello"));
assertEquals(p.getCode("Hello"), 5);
}
Page 9 of 18
Mr. RAGHU
EXAMPLE#2
Annotations based:
@Mock: Creates A Mock object of a type
@InjectMock: Injects the Dependency Mock objects
@ExtendWith(MockitoExtension.class) : Enable Mockito annotations with JUnit
SERVICE CODE: -
package com.app.raghu;
import java.sql.SQLException;
import java.util.List;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Page 10 of 18
Mr. RAGHU
}
}
}
TEST CLASS: -
package com.app.raghu;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
Repository repository;
@InjectMocks
Service service;
@Test
void testSuccess() {
// Setup mock scenario
try {
Mockito.when(repository.getData()).thenReturn(
Arrays.asList("A", "B", "CDEFGHIJK", "12345", "1234"));
} catch (SQLException e) {
e.printStackTrace();
}
Page 11 of 18
Mr. RAGHU
Assertions.assertNotNull(data);
Assertions.assertEquals(3, data.size());
}
@Test
void testException() {
// Setup mock scenario
try {
Mockito.when(repository.getData()).thenThrow(
new SQLException("Connection Exception"));
} catch (SQLException e) {
e.printStackTrace();
}
Page 12 of 18
Mr. RAGHU
Entity:
package com.app.raghu.entity;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "moviestab")
public class Movie {
Page 13 of 18
Mr. RAGHU
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Repository:
package com.app.raghu.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.app.raghu.entity.Movie;
TEST CASE:
package com.app.raghu;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
Page 14 of 18
Mr. RAGHU
import com.app.raghu.entity.Movie;
import com.app.raghu.repo.MovieRepository;
@DataJpaTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MovieRepositoryTest {
@Autowired
private MovieRepository movieRepository;
@Order(1)
@Test
@DisplayName("IT SHOULD SAVE THE MOVIE TO THE DATABASE")
void save() {
Movie avatarMovie = new Movie();
avatarMovie.setName("Avatar");
avatarMovie.setGener("Action");
avatarMovie.setReleaseDate(LocalDate.of(2000, Month.APRIL, 23));
@Order(2)
@Test
@DisplayName("IT SHOULD RETURN THE MOVIES LIST WITH SIZE OF 2")
void getAllMovies() {
Movie rrr = new Movie();
rrr.setName("RRR");
rrr.setGener("Action");
rrr.setReleaseDate(LocalDate.of(2022, Month.MARCH, 24));
movieRepository.save(rrr);
assertNotNull(list);
Page 15 of 18
Mr. RAGHU
assertThat(list).isNotNull();
assertEquals(2, list.size());
}
@Order(3)
@Test
@DisplayName("IT SHOULD RETURN THE MOVIE BY ITS ID")
void getMovieById() {
Movie rrr = new Movie();
rrr.setName("RRR");
rrr.setGener("Action");
rrr.setReleaseDate(LocalDate.of(2022, Month.MARCH, 24));
movieRepository.save(rrr);
assertNotNull(newMovie);
assertEquals("Action", newMovie.getGener());
assertThat(newMovie.getReleaseDate()).isBefore(LocalDate.of(2022, Month.APRIL, 24));
}
@Order(4)
@Test
@DisplayName("IT SHOULD RETURN THE MOVIES LIST WITH GENER THRILLER")
void getMoviesByGenera() {
Movie rrr = new Movie();
rrr.setName("RRR");
rrr.setGener("Action");
rrr.setReleaseDate(LocalDate.of(2022, Month.MARCH, 24));
movieRepository.save(rrr);
assertNotNull(list);
assertThat(list.size()).isEqualTo(1);
}
@Order(5)
Page 16 of 18
Mr. RAGHU
@Test
@DisplayName("IT SHOULD UPDATE THE MOVIE GENERA WITH FANTACY")
void updateMovie() {
Movie rrr = new Movie();
rrr.setName("RRR");
rrr.setGener("Action");
rrr.setReleaseDate(LocalDate.of(2022, Month.MARCH, 24));
movieRepository.save(rrr);
assertEquals("Fantacy", updatedMovie.getGener());
assertEquals("RRR", updatedMovie.getName());
}
@Order(6)
@Test
@DisplayName("IT SHOULD DELETE THE EXISTING MOVIE")
void deleteMovie() {
Movie kantara = new Movie();
kantara.setName("KANTARA");
kantara.setGener("Thriller");
kantara.setReleaseDate(LocalDate.of(2022, Month.SEPTEMBER, 30));
movieRepository.save(kantara);
Long id = kantara.getId();
movieRepository.delete(kantara);
assertEquals(1, list.size());
assertThat(exitingMovie).isEmpty();
Page 17 of 18
Mr. RAGHU
FB: http://facebook.com/groups/thejavatemple
Page 18 of 18