Junit Test with Maven

In this post I will explain how to create and run JUnit test using maven. download Apache maven from link “download”, extract zip package into you machine and setup path maven bin folder into your system  environment variable. following are the steps to create JUnit test for maven and maven commands.

JUnit Test creation:

Create source folder in your eclipse “src/test/java” and “src/main/java” as below screen:

JUnit test  must be created into source folder “src/test/java”  I have created  two junit test into package com.test” of “src/test/java” source folder.



Junit1Test.java

 package com.test;

 import org.junit.*;

 public class JunitScript1Test {

    @BeforeClass
    public static void beforeClassAnnotation() {        
      System.out.println("@BeforeClass - for junit class 1");
    }

    @AfterClass
    public static void afterClassAnnotation() {       
      System.out.println("@AfterClass - for junit class 1");
    }  

    @Test
    public void testAnnotation() {       
        System.out.println("@Test - first class test method");
    }    
 } 


Junit2Test.java

 package com.test;

import org.junit.*;

public class JunitScript2Test {

    @BeforeClass
    public static void beforeClassAnnotation() {        
      System.out.println("@BeforeClass - for junit class 2");
    }

    @AfterClass
    public static void afterClassAnnotation() {       
      System.out.println("@AfterClass - for junit class 2");
    }  

    @Test
    public void testMethod2() {       
        System.out.println("@Test - Second class test method");
    }    
}


Create pom.xml file as below.

 <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>maven-junit-test</groupId>
   <artifactId>maven-junit-test</artifactId>
   <packaging>jar</packaging>
   <version>1.0</version>
   <name>maven-junit-test</name>
 
   <dependencies>
     <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.5</version>
       <scope>test</scope>
     </dependency>    
     
  </dependencies>
</project>


Test Execution:

Run command if you want to clear previous build

      mvn clean     

Run command to build your code.

      mvn install     

Run command to execute all junit test

      mvn test     

After execution above command all junit test executed and console look like below.
Run below command in case of one junit test execution

      mvn –Dtest=JunitScript2Test test  

while executing above command only “JunitScript2Test” be executed.

No comments:

Post a Comment

Leave your comments, queries, suggestion I will try to provide solution