VOOZH about

URL: https://www.geeksforgeeks.org/software-testing/junit-testing-for-mysql-project-in-java/

⇱ JUnit Testing For MySQL Project in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JUnit Testing For MySQL Project in Java

Last Updated : 5 May, 2026

JUnit testing plays a vital role in validating Java applications that interact with databases like MySQL. It helps ensure that database operations such as fetching, inserting, and updating data work correctly and reliably.

  • Automates testing of database-driven logic
  • Reduces human errors compared to manual testing
  • Improves code quality and reliability

Steps for JUnit Testing with MySQL

Follow below steps to setting up and testing a MySQL-based Java application using JUnit to ensure correct database operations.

Step 1: Create Maven Project

1. Open IntelliJ IDEA
2. Click New Project
3. Select Maven
4. Choose JDK (Java 8 or above)
5. Enter details:

  • GroupId: geeksforgeeks
  • ArtifactId: jdbc.com

6. Click Finish

Project Structure:

After creation, your project should look like:

👁 Project Structure
 

Step 2: Add Dependencies

Relevant Maven dependency for JUnit. This has to be available in pom.xml

pom.xml

Step 3: Setup MySQL Database

Let us assume that MySQL got installed in the system and there is a database named "geeksforgeeks" is available

👁 Image

Step 4: Create Properties File

Let us see the important files of the project.

ds-connection.properties

ds.database-driver=com.mysql.jdbc.Driver
ds.url=jdbc:mysql://localhost:3306/geeksforgeeks
ds.username=root
ds.password=your_password

Step 5: Create Connection Class

ConnectionClass.java

Step 6: Create Model Class

Each and every field should match with the corresponding freelancer table(MySQL) column

Freelancer.java

Step 7: Create DAO Class

FreelancerQueries.java

Now, let us see the JUnit test case preparation file. Here we have to include positive, and negative scenarios for each and every requirement. Multiple assert statements we can write in a method and all should get passed and that will tell about our software code is correct in all aspects and for any test data, the written code will be correct.

Step 8: Write JUnit Test Cases

Each and every method has to start with @Test and inside the method, the methods written in "FreelancerQueries.java" should be called. Testcases can be written with

  • assertEquals (Equality checking)
  • assertNotEquals(Not equality checking)
  • assertTrue(Checking for True) etc.,

AppTest.java

Let us execute the JUnit test cases now. We have to run the test cases in the following way

👁 Image

Once everything is successful, we will get the output as follows

👁 Image

In cases of any error, it will be clearly indicated as follows :

👁 Image
Comment
Article Tags:

Explore