0% found this document useful (0 votes)
31 views18 pages

JUnit Document

Uploaded by

mouneshgs96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views18 pages

JUnit Document

Uploaded by

mouneshgs96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Mr.

RAGHU

JUNIT5 AND MOCKITO4


JUnit

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

 Launches testing frameworks on the JVM


 Has TestEngine API used to build a testing framework that runs on the 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

JUnit Maven Dependencies

 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

Listed below are some commonly used annotations provided in it:

Annotation Description .

@Test Denotes a test method

@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

@Disable Used to disable a test class or test method

@Tag Declare tags for filtering tests

@ExtendWith Register custom extensions

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 .

assertEquals(expected, actual) Fails when expected does not equal actual

assertFalse(expression) Fails when expression is not false

assertNull(actual) Fails when actual is not null

assertNotNull(actual) Fails when actual is null

Page 2 of 18
Mr. RAGHU

assertAll() Group many assertions and every assertion is executed even if one
or more of them fails

assertTrue(expression) Fails if expression is not true

assertThrows() Class to be tested is expected to throw an exception

@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;

public class Calculator {

public int multiply(int a, int b) {


return a * b;
}
}

TEST CLASS: -
package com.app.raghu;

import static org.junit.jupiter.api.Assertions.assertEquals;


import static org.junit.jupiter.api.Assertions.assertNotEquals;

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

assertEquals(20, calculator.multiply(4, 5),


"Regular multiplication should work");
}

@Test
@Order(10)
//@Disabled
void testZero() {
assertNotEquals(100, calculator.multiply(4, 0),
"Regular multiplication should work");
}

@AfterEach
void clean() {
calculator = null;
}
}

JUNIT TEST FOR DATABASE CONNECTION SINGLETON TESTING


pom.xml
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>

SERVICE CLASS: -
package com.app.raghu;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionUtil {

private static Connection con = null;

static {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bootdb",
"root", "root");
} catch (SQLException e) {
e.printStackTrace();

Page 6 of 18
Mr. RAGHU

}
}

public static Connection getConnection() {


return con;
}
}

TEST CLASS: -
package com.app.raghu;

import static org.junit.jupiter.api.Assertions.assertAll;


import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;

import java.sql.Connection;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ConnectionUtilTest {

Connection con1, con2;

@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.

What are Benefits of Mocking?

No handwriting: In Mockito, there is no requirement for writing your mock objects.


Safe refactoring: While renaming the method name of an interface or interchanging the parameters do
not change the test code, as mock objects are created at runtime.

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.

Creating Mock Object for a class:


T obj = mock(T.class)

Provide Implementation to mock object (We can call training even)


To Return a value:
when(obj.method()).thenReturn(output)
To throw any exception:
when(obj.method()).thenThrow(exceptionObj)
Mocking Void methods:
doNothing().when(instance).methodName();

EXAMPLE#1
Service Code:
package com.app.raghu;

public interface ProcessInfo {

Integer getCode(String code);


}

Mocking with Methods:


package com.app.raghu;

import static org.junit.jupiter.api.Assertions.assertEquals;


import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;

public class ProcessInfoTest {


@Test
void testgetCode() {
ProcessInfo p = mock(ProcessInfo.class);
when(p.getCode("Hello")).thenReturn(5);

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;

public class Repository {


public List<String> getData() throws SQLException {
return null;
}
}
-------------------------------------------------------------------
package com.app.raghu;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Service {


private Repository repository;

public Service(Repository repository) {


this.repository = repository;
}

public List<String> getDataLen() {


try {
return repository.getData().stream()
.filter(data -> data.length() < 5)
.collect(Collectors.toList());
} catch (SQLException e) {
return Arrays.asList();

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();
}

// Execute the service that uses the mocked repository


List<String> data = service.getDataLen();

// Validate the response

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();
}

// Execute the service that uses the mocked repository


List<String> data = service.getDataLen();

// Validate the response


Assertions.assertNotNull(data);
Assertions.assertEquals(0, data.size());
}
}

SPRING BOOT TESTING EXAMPLES


EXAMPLE#3 Spring Boot Data JPA JUnit with Mock Example
Dependencies: Data JPA, H2, Lombok

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;

private String name;

private String gener;

private LocalDate releaseDate;


}

Repository:
package com.app.raghu.repo;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.raghu.entity.Movie;

public interface MovieRepository extends JpaRepository<Movie, Long>{

List<Movie> findByGener(String gener);


}

TEST CASE:
package com.app.raghu;

import static org.assertj.core.api.Assertions.assertThat;


import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

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));

Movie newMovie = movieRepository.save(avatarMovie);


assertNotNull(newMovie);
assertThat(newMovie.getId()).isNotEqualTo(null);
}

@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);

Movie kantara = new Movie();


kantara.setName("KANTARA");
kantara.setGener("Thriller");
kantara.setReleaseDate(LocalDate.of(2022, Month.SEPTEMBER, 30));
movieRepository.save(kantara);

List<Movie> list = movieRepository.findAll();

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);

Movie newMovie = movieRepository.findById(rrr.getId()).get();

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);

Movie kantara = new Movie();


kantara.setName("KANTARA");
kantara.setGener("Thriller");
kantara.setReleaseDate(LocalDate.of(2022, Month.SEPTEMBER, 30));
movieRepository.save(kantara);

List<Movie> list = movieRepository.findByGener("Thriller");

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);

Movie existingMovie = movieRepository.findById(rrr.getId()).get();


existingMovie.setGener("Fantacy");
Movie updatedMovie = movieRepository.save(existingMovie);

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();

Movie rrr = new Movie();


rrr.setName("RRR");
rrr.setGener("Action");
rrr.setReleaseDate(LocalDate.of(2022, Month.MARCH, 24));
movieRepository.save(rrr);

movieRepository.delete(kantara);

List<Movie> list = movieRepository.findAll();

Optional<Movie> exitingMovie = movieRepository.findById(id);

assertEquals(1, list.size());
assertThat(exitingMovie).isEmpty();

Page 17 of 18
Mr. RAGHU

EXAMPLE#4 Spring Boot Rest JUnit with Mock Example

FB: http://facebook.com/groups/thejavatemple

Page 18 of 18

You might also like