JUnit test with MySQL database instance running inside a testcontainer using IntelliJ IDEA

JUnit is one of the most popular unit testing frameworks used with Java to create repeatable tests. With JUnit each test is written as a separate method inside a Java class. IntelliJ IDEA provides an option to run these test cases from within the IDE.

In case you have a module that communicates with a MySQL database, you can unit test the module by providing it access to a MySQL server running inside a testcontainer. You can also configure this MySQL database instance with your desired username, password and database name (in MySQL server) using the API provided by Testcontainers framework.

In case you use Maven to manage dependencies in your project, as used in Appsmith , you can add the following snippet in your POM file to include all the required packages:


To create a new MySQL testcontainer instance with JUnit 4 you may follow these steps as used in Appsmith's unit test file to test its MySQL plugin:

public static MySQLContainer mySQLContainer = new MySQLContainer("mysql:5.7")

Please note that Testcontainers framework is different for JUnit4 and JUnit5. Please use the framework as per the JUnit version that you have used. For more details please see Testcontainers page.

Databases spwaned using Testcontainers when run from within the IDE can seem to become inaccessible from outside the IDE. In order to connect to such databases you can uses the database tool that comes with IDEA ultimate version.

Steps to connect to the MySQL database:

  1. Add a debug point in the code such that the testcontainer has been brought up at this point. Screenshot 2020-12-17 at 10.58.27 AM.png

  2. Run the test program using debug mode and wait till it stops on the break point. Screenshot 2020-12-17 at 10.59.27 AM.png Screenshot 2020-12-17 at 11.09.16 AM.png

  3. Click on the database tool. Screenshot 2020-12-17 at 11.10.00 AM.png

  4. Select your database type. Screenshot 2020-12-17 at 11.12.06 AM.png

  5. Fetch your credentials. You may read the credentials from the testcontainer using the following API when using with JUnit 4.

    address  = mySQLContainer.getContainerIpAddress();
    port     = mySQLContainer.getFirstMappedPort();
    username = mySQLContainer.getUsername();
    password = mySQLContainer.getPassword();
    database = mySQLContainer.getDatabaseName();
  6. Test your connection and save credentials. Screenshot 2020-12-17 at 11.17.17 AM.png

  7. Run query. Screenshot 2020-12-17 at 11.19.44 AM.png

No Comments Yet