18. How to Test Spring Boot Service Classes Using Testcontainers and JUnit 5

Follow these steps to create and run unit tests for the service class in your Spring Boot CRUD application:

Create an application.properties file under test > java > resources.

Copy and paste the content for the application.properties file from the GitHub repository.

Add the required dependencies to your pom.xml file by copying them from the GitHub repository.

Implement the ServiceTest class.

Implement the MySQLContainer function and configure properties for the data source.

Create a setup function annotated with @BeforeEach to initialize and set the object parameters before each test.

Implement the save function test.

Run the saveBook test function.

The Testcontainers library will install the necessary MySQL container on Docker Desktop. After installation, the test functions will run and display the test results.

Implement the remaining test functions as needed.

Run the ServiceTest class to test all functions.

Test results will indicate whether each function passes or fails.

You can find the related GitHub repository branch here: book-details-unit_test-service_class-test_Container

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.datasource.username=test
spring.datasource.password=test
spring.jpa.hibernate.ddl-auto=update

BookServiceTest.java

package com.codersstash.book_details.Service;

import com.codersstash.book_details.entity.Book;
import com.codersstash.book_details.repository.BookRepository;
import com.codersstash.book_details.service.BookService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.util.List;

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

@Testcontainers
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class BookServiceTest {
    @Container
    static MySQLContainer<?> mysql=new MySQLContainer<>("mysql:8.0.41")
            .withDatabaseName("test_db")
            .withUsername("test")
            .withPassword("test");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry){
        registry.add("spring.datasource.url",mysql::getJdbcUrl);
        registry.add("spring.datasource.username",mysql::getUsername);
        registry.add("spring.datasource.password",mysql::getPassword);
    }

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private BookService bookService;

    private Book book;

    @BeforeEach
    void setup(){
        book=new Book();
        book.setBook_name("Test Book");
        book.setBook_author("Test Author");
        book.setBook_publisher("Test Publisher");
        book.setBook_description("Test Description");
        book.setBook_price(49.99);
    }

    @Test
    @Order(1)
    void saveBook_ShouldPersistBook(){
        Book savedBook=bookService.saveBook(book);

        assertNotNull(savedBook);
        assertEquals("Test Book",savedBook.getBook_name());
    }

    @Test
    @Order(2)
    void getBookById_ShouldReturnBook(){
        Book savedBook=bookService.saveBook(book);
        Book foundBook=bookService.getBookById(savedBook.getBook_id());

        assertNotNull(foundBook);
        assertEquals(savedBook.getBook_id(),foundBook.getBook_id());
    }

    @Test
    @Order(3)
    void getAllBooks_shouldReturnBooksList(){
        bookService.saveBook(book);
        List<Book> books=bookService.getAllBooks();

        assertFalse(books.isEmpty());
        assertTrue(books.size()>0);
    }

    @Test
    @Order(4)
    void deleteBook_ShouldRemoveBook(){
        Book savedBook=bookService.saveBook(book);
        bookService.deleteBook(savedBook.getBook_id());

        assertNull(bookService.getBookById(savedBook.getBook_id()));
    }
}

pom.xml

<dependency>
			<groupId>org.testcontainers</groupId>
			<artifactId>junit-jupiter</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-testcontainers</artifactId>
			<scope>test</scope>
</dependency>

Leave a Reply

Your email address will not be published. Required fields are marked *