Setting up Java JUnit Project with Eclipse + Maven Example


  1. In Eclipse, go to File -> New -> Other...
  2. Now Select Maven -> Maven Project
  3. Click Next,
  4. Select "Create a simple project (Skip archetype selection)", Next
  5. Enter Group Id and Artifact Id and click Finish.
  6. Now open the pom.xml and add the following dependency for Junit 4 under dependencies,
    	<dependencies>
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.8.1</version>
    			<scope>test</scope>
    		</dependency>
    	</dependencies>
  7. Create a java file,
    package myprog;
    
    public class Addition {
    	
    	public int add (int no1, int no2) {
    		return no1 + no2;
    	}
    }
    
  8. Now write a text class for the class we created under src/test/java package,
    package myprog;
    
    import static org.junit.Assert.assertEquals;
    
    import org.junit.Test;
    
    public class AdditionTest  {
    
    	@Test
    	public void addTwoNumbers() {
    		Addition addition = new Addition();
    		assertEquals(5, addition.add(2, 3));
    	}
    	
    }

Now let's run the maven test command to run the test cases, simply right click on your project folder and select Run As -> Maven test

Run Maven Junit text in Eclipse IDE
Junit 4 test run results in Eclipse using Maven

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap