
If you are working with a Apache Maven Java project and want to run your unit test cases, you would need to do the following,
1. Add Java JUnit dependencies to pom.xml
Open pom.xml file and the junit dependency as highlighted in bold, you can find the details on official JUnit website: https://junit.org/junit4/dependency-info.html
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>maven-juit-proj</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
</dependencies>
</project>
2. The Java Project Structure
I am using Idea IntelliJ IDE on macOS, and my project structure is as below,

public class HelloWorld {
public String greeting(String name) {
return "Hello, " + name;
}
}
HelloWorldTest.java
import org.junit.Test;
import org.junit.Assert;
public class HelloWorldTest {
private HelloWorld hello = new HelloWorld();
@Test
public void test() {
Assert.assertEquals("Hello, Neo", hello.greeting("Neo"));
}
}
3. Running Maven Test
Now that we have our simple HelloWorld class and its HelloWorldTest class ready with the JUnit 4 dependency set in our pom.xml we are ready to run our text using maven commands,
⛔️ Make sure Maven is installed on your computer if not check out this article: How to install maven in macOS using Terminal Command
✏️ Command: mvn test - to run all the test cases in our project
[email protected] maven-juit-proj % mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< org.example:maven-juit-proj >---------------------
[INFO] Building maven-juit-proj 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ maven-juit-proj ---
[WARNING] Using platform encoding (US-ASCII actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ maven-juit-proj ---
[WARNING] Using platform encoding (US-ASCII actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ maven-juit-proj ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding US-ASCII, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /Users/code2care/IdeaProjects/maven-juit-proj/target/classes
[INFO]
Downloading from central:
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit4/2.12.4/surefire-junit4-2.12.4.pom
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit4/2.12.4/surefire-junit4-2.12.4.pom
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-providers/2.12.4/surefire-providers-2.12.4.pom
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-providers/2.12.4/surefire-providers-2.12.4.pom
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit4/2.12.4/surefire-junit4-2.12.4.jar
https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit4/2.12.4/surefire-junit4-2.12.4.jar
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running HelloWorldTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.04 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.241 s
[INFO] Finished at: 2021-02-13T14:51:48+05:30
[INFO] ------------------------------------------------------------------------
Let's add one more test case that would fail,
@Test
public void test2() {
Assert.assertEquals("Hello, Neo", hello.greeting("Sam"));
}
mvn test output:
Running HelloWorldTest
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.038 sec <<< FAILURE!
test2(HelloWorldTest) Time elapsed: 0.003 sec <<< FAILURE!
org.junit.ComparisonFailure: expected:<[Hello, Neo]> but was:<[Sam]>
at org.junit.Assert.assertEquals(Assert.java:117)
at org.junit.Assert.assertEquals(Assert.java:146)
at HelloWorldTest.test2(HelloWorldTest.java:15)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.
....
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: test2(HelloWorldTest): expected:<[Hello, Neo]> but was:<[Sam]>
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.760 s
[INFO] Finished at: 2021-02-13T15:24:00+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project maven-juit-proj: There are test failures.
[ERROR]
[ERROR] Please refer to /Users/code2care/IdeaProjects/maven-juit-proj/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
✏️ Command: mvn -Dtest=<Test-Class-Name> test
To run individual test,
Example:
$ mvn -Dtest=HelloWorldTest test
✏️ Command: mvn -Dtest=<Test-Class-Name-1>,<Test-Class-Name-2 test
To run multiple tests at once.
Example:
$ mvn -Dtest=HelloWorldTest, HelloWorldTest2 test
✏️ Command: mvn -Dtest=<Test-Class-Name-1>#methodName test
To run a particular test method from a class.
Example:
$ mvn -Dtest=HelloWorldTest#test test
✏️ Command: mvn -Dtest=<Test-Class-Name-1>#methodName* test
To run all test methods what that matches the regular expression,
Example:
$ mvn -Dtest=HelloWorldTest#test* test
The above will run test and test1 methods from class HelloWorldTest
- Java XML-RPC 3.1.x based web service example
- List of jars required for Struts2 project
- list of jars required for hibernate 4.x.x
- How to create StackOverflow error in java
- Tutorial Java SOAP WebServices JAS-WS with Eclipse J2EE IDE and Tomcat Server Part 1
- import servlet API to eclipse project (javax.servlet cannot be resolved error)
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- Convert String to int in Java
- JSP Hello World Program Tutorial with Eclipse and Tomcat Server
- SharePoint Open in the client application document opens in browser
- Java: TimeZone List with GMT/UTC Offset
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Remove Trailing zeros BigDecimal Java
- [Solution] Java Error Code 1603. Java Update did not complete.
- Maven Eclipse (M2e) No archetypes currently available
- error: file not found: HelloWorld.java
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to check if Java main thread is alive
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- Java XML-RPC java.net.BindException: Address already in use
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end users experience
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- List of jar files for Jax-ws (SOAP) based Java Web Services
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- Maven Unsupported major.minor version 51.0
- hibernate.cfg.xml Configuration and Mapping xml Example
- How to verify if java is installed on the computer and get version detail
- Unhandled exception type InterruptedException : Java Threads
- XmlRpcException ConnectException connection refused error
- Error: Unable to access jarfile jarFileName.jar file [Windows]
- BeanDefinitionStoreException IOException parsing XML document from class path resource [spring.xml]
- How to serialize-deserialize an object in java
- List of Java Keywords
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server
- Struts 2 Hello World Example in Eclipse
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- List of Java versions
- Create simple struts2 project using maven commands
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- Error: Can not find the tag library descriptor for
- connection.url property value in hibernate.cfg.xml for mysql
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Setting Java_Home Environment variable on Windows Operating System
- Android : Error in http connection java.net.SocketException: Permission denied - Android
- How to create Toast messages in Android - Android
- How to Search Something (string) in Android Studio Project like Eclipse - Android-Studio
- How to detect Browser and Operating System Name and Version using JavaScript - JavaScript
- Free Unlimited Calls from MTNL & BSNL Landlines from 1st May 2015 - HowTos
- Adding internet permission to Android Project - Android
- How to turn off Facebook autoplay videos on timeline - Facebook
- Android : How to make TextView Scrollable - Android
- Sharepoint Server 2016 installation Prerequisites with download links - SharePoint
- How to get current URL Location using Javascript HTML - JavaScript
- Android Toast position top - Android
- How to submit website to dmoz directory - HowTos
- SharePoint Server 2016 setup error - A system restart from a previous installation or update is pending. Restart your computer and run setup to continue. - SharePoint
- Java XML-RPC 3.1.x based web service example - Java
- Plug-in com.android.ide.eclipse.adt was unable to lead class Error - Android