Search code examples
javamavenintellij-idea

How to run tests using maven


When I run the command mvn test in my java project, it shows 0 tests run. There is a single test file under src/test/java named xyzTest.java Although I can go to it and right-click on the Test file inside Intellij Idea and run all the tests in the file.
I was wondering how I could do the same in the command line.
Currently, there are only dependencies in the pom.xml I am not using any plugins. I read that the surefire maven plugin could help with this. But I find it strange to have to add a plugin to execute such a simple thing. How does IntelliJ run it when one right-clicks on the file and runs it?
Is there an alternative or any way to run all the tests?
I am able to run the main file through using the command line by executing mvn exec:java


Solution

  • You'll need to add the Surefire plugin. From the Maven Surefire Plugin documentation: "The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application."

    From the Usages page: "Best practice is to define the version of the Surefire Plugin that you want to use in either your pom.xml or a parent pom.xml:

    <project>
      [...]
      <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>3.0.0</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
      [...]
    </project>
    

    The Surefire Plugin can be invoked by calling the test phase of the build lifecycle.

    mvn test
    

    " You can run mvn test if you want to run Maven phases up to and including test, or mvn clean verify if you want to rebuild and test your project.

    While I understand you might find it strange to have to add a plugin to execute such a simple thing, this is how Maven works. From the Maven documentation on Plugins: "Maven is - at its heart - a plugin execution framework; all work is done by plugins."