All Projects → rashidi → spring-boot-tc-mysql

rashidi / spring-boot-tc-mysql

Licence: Unlicense license
Sample Spring Boot application that uses MySQL to perform integration tests by using TestContainer.

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to spring-boot-tc-mysql

saloon
An E2E test seeder for enterprise web applications
Stars: ✭ 30 (+42.86%)
Mutual labels:  test-automation
test junkie
Highly configurable testing framework for Python
Stars: ✭ 72 (+242.86%)
Mutual labels:  test-automation
testcafe-testing-library
🐂 Simple and complete custom Selectors for Testcafe that encourage good testing practices.
Stars: ✭ 68 (+223.81%)
Mutual labels:  test-automation
bokor
Bokor is a simple, Record and Playback Mock Server written in Node.js, utilized for Service Virtualization.
Stars: ✭ 24 (+14.29%)
Mutual labels:  test-automation
picire
Parallel Delta Debugging Framework
Stars: ✭ 41 (+95.24%)
Mutual labels:  test-automation
qt monkey
Tool for testing Qt based applications
Stars: ✭ 39 (+85.71%)
Mutual labels:  test-automation
MasterSeleniumFramework
Automation Testing | Web | Java | OOPS | Selenium WebDriver | TestNG | Maven | ExtentReport | Allure Reports | Java mail API | Design Patterns (Page Object Model, Singleton) | Jenkins | Data-Driven Testing using JSON file
Stars: ✭ 52 (+147.62%)
Mutual labels:  test-automation
bdd-for-all
Flexible and easy to use library to enable your behavorial driven development (BDD) teams to easily collaborate while promoting automation, transparency and reporting.
Stars: ✭ 42 (+100%)
Mutual labels:  test-automation
cleanarchitecture-sample
Sample REST API demonstrating the clean architecture
Stars: ✭ 43 (+104.76%)
Mutual labels:  sample-app
door-controller-test-tool
Door controller test tool for physical access control devices. (THIS PROJECT IS NO LONGER MAINTAINED)
Stars: ✭ 13 (-38.1%)
Mutual labels:  test-automation
flybirds
基于自然语言的,跨端跨框架 BDD UI 自动化测试方案,BDD testing, Python style, Present by Trip Flight
Stars: ✭ 701 (+3238.1%)
Mutual labels:  test-automation
play-scala-tls-example
A Play application using HTTPS and WS with optional client authentication
Stars: ✭ 44 (+109.52%)
Mutual labels:  sample-app
laravel-test-watcher
Laravel Test Watcher
Stars: ✭ 20 (-4.76%)
Mutual labels:  test-automation
sandboni-core
Sandboni - Java test optimization library which reduces test execution time without compromising quality
Stars: ✭ 27 (+28.57%)
Mutual labels:  test-automation
fast-test
fast-test是基于Java的自动化测试工具集合,包含自动测试平台(后端Vue),自动测试框架,可以帮助测试人员快速构建各类测试工具和自动化测试框架。请点星支持!
Stars: ✭ 112 (+433.33%)
Mutual labels:  test-automation
test-automation-bootstrap
A simple and effective boilerplate repo to quickstart test automation frameworks ✨
Stars: ✭ 42 (+100%)
Mutual labels:  test-automation
carina
Carina automation framework: Web, Mobile, API, DB etc testing...
Stars: ✭ 652 (+3004.76%)
Mutual labels:  test-automation
main
Mocks Server monorepo
Stars: ✭ 109 (+419.05%)
Mutual labels:  test-automation
frisbee
A Kubernetes Framework for Cloud-Native Application Testing
Stars: ✭ 39 (+85.71%)
Mutual labels:  test-automation
play-java-fileupload-example
An example Play application showing custom multiform fileupload in Java
Stars: ✭ 13 (-38.1%)
Mutual labels:  sample-app

Spring Boot: MySQL Container Integration

Avoid running different databases between integration tests and production.

Maven Build

Background

In general, we tend to use H2 to perform integration tests within the application. However there are scenarios where H2 may not give the same outcome as our actual database, such as MySQL. Such scenario is when you have a table column called rank or order.

Both names are allowed with H2 database but not with MySQL as those are reserved keywords. Therefore it is best to use the same database, in production environment, for our integration tests.

In this guide, we will implement MySQL Container, from TestContainers, with Spring Boot.

Dependencies

Full dependencies can be found in pom.xml.

Database

  • spring-boot-starter-data-jpa
  • spring-boot-starter-data-rest
  • mysql-connector-java

Integration tests

  • junit-jupiter from TestContainers
  • mysql from TestContainers

Implementation

Entity Class

Given we have a class called Book along with its repository class, BookRepository.

@Data
@Entity
public class Book {

    @Id
    @GeneratedValue
    private Long id;

    @Embedded
    private Author author;

    private String title;

}
public interface BookRepository extends JpaRepository<Book, Long> {
}

Test Implementation

Here we will be utilizing MySQL module from TestContainers to perform integration tests. The following implementation can be found in BookRepositoryRestResourceTests

Enable TestContainers

org.testcontainers:junit-jupiter dependency simplifies our implementation whereby the dependency will handle the
start and stop of the container.

We will start by informing @SpringBootTest that we will be using ContainerDatabaseDriver as our driver class
along with our JDBC URL

@Testcontainers
@SpringBootTest(
        properties = {
                "spring.jpa.generate-ddl=true",
                "spring.datasource.url=jdbc:tc:mysql:8:///test
        }
)
public class BookRepositoryRestResourceTests {

}

We will trigger a REST call to create a Book and given that there is a database running, the book should be created.

@Testcontainers
@SpringBootTest(
        properties = {
                "spring.jpa.generate-ddl=true",
                "spring.datasource.url=jdbc:tc:mysql:8:///test
        },
        webEnvironment = RANDOM_PORT
)
public class BookRepositoryRestResourceTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @DisplayName("Entity will be created if datasource is available")
    void create() {
        var author = author();

        var book = book(author);

        ResponseEntity<Book> response = restTemplate.postForEntity("/books", book, Book.class);

        assertThat(response.getStatusCode()).isEqualTo(CREATED);
    }

    private Author author() {
        var author = new Author();

        author.setName("Rudyard Kipling");

        return author;
    }

    private Book book(final Author author) {
        var book = new Book();

        book.setAuthor(author);
        book.setTitle("The Jungle Book");

        return book;
    }

}

Execute the test and you will get HTTP 200 or CREATED returned. To be certain that our test did run with MySQL Container, we should see the following content in the logs:

DEBUG 🐳 [mysql:8] - Starting container: mysql:8
...
org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect

This is how the application informing us that it is using MySQL Container which lead to Spring Boot automatically configure our dialect to MySQL8Dialect.

Verify MySQL availability

Another option is to verify that our application will connect to MySQL by triggering a check against Spring Boot Actuator Health endpoint.

public class DatasourceHealthTests {

    @Test
    @DisplayName("Database status will be UP and Database name should be MySQL")
    void databaseIsAvailable() throws JsonProcessingException {
        var response = restTemplate.getForEntity("/actuator/health", String.class);

        assertThat(response.getBody()).isNotNull();

        JsonNode root = new ObjectMapper().readTree(response.getBody());
        JsonNode dbComponentNode = root.get("components").get("db");

        String dbStatus = dbComponentNode.get("status").asText();
        String dbName = dbComponentNode.get("details").get("database").asText();

        assertThat(dbStatus).isEqualTo("UP");
        assertThat(dbName).isEqualTo("MySQL");
    }

}

Test above verifies that there's a running MySQL database connected to the application. Full implementation can be found in DatasourceHealthTests.

Conclusion

Now that we are running the same database as production environment, we can expect more accurate results from our integration tests.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].