'how to prevent jdbc from trying to connect to a mysql database during unit testing

I'm making an application for a school project, but I'm running into the issue that when I try to run the unit tests that it tries to connect to the database while starting up the application, which isn't required for the tests (because it will be mocked), and is not available in the CI/CD pipeline.

jdbc connection error

I'm building my project in Java Maven Springboot and would like to know how I can prevent it from trying to connect to the database when running my test.

here is a link to my repository: https://gitlab.com/kwetter_jack/Kwetter_posts/-/tree/ci_cd_setup



Solution 1:[1]

while I was investigating the spring boot H2 in-memory database (as suggested by Chris Olive and Paranaaan) I also came across the option of using a test container. after looking into this I saw that this enables the project to create a temp docker container with a MySQL image that I can use during the testing of my project, considering I was planning on using docker anyway for the integration testing of my microservices project I attempted this and it worked as I had hoped it would.

if anyone is interested in the test container solution that I used, the information can be found here:

https://www.testcontainers.org/modules/databases/mysql/

Solution 2:[2]

Your test classes have @SpringBootTest annotation which will start a Spring application context - as your application uses a database the tests will also try to setup and use a database connection.

The simplest solution is to remove the annotation so the tests no longer try to connect to a database. You'll probably need to mock some more dependencies as a result as Spring is no longer creating these for you. You could also have a look at https://www.baeldung.com/spring-boot-testing for some other ideas how you could alter your tests.

Alternatively if you do want / need the application context to run you can add a application.yaml for the tests that defines and uses a in memory DB so the tests have something to connect to - see https://www.baeldung.com/spring-boot-h2-database for details how to do this.

Solution 3:[3]

Just change value under spring.datasource to H2 database to prevent The application connect the real database.

Test application.yml

FYI, You no need to copy all config from original application.yml, just only some config that you need to override.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Chris Olive
Solution 3 paranaaan