Home > OS >  how to prevent jdbc from trying to connect to a mysql database during unit testing
how to prevent jdbc from trying to connect to a mysql database during unit testing

Time:05-12

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related