Calculator JUnit Tests in Maven Project
Introduction
In this tutorial, we will create a simple Maven project with Calculator tests and run the JUnit tests in the Maven build process.
Create Maven Project
We can use the quick start archetype to create a simple Maven project with basic project directory structure.
https://www.testingdocs.com/create-quickstart-maven-project-in-eclipse-ide/
Calculator Tests
Add code for the Calculator class and the corresponding tests for the calculator object. Example Calculator code and tests are at:
https://www.testingdocs.com/junit-calculator-test-case-example/
Project Structure
Java code to be tested goes under src/main/java
Test code goes under src/test/java
Maven surefire plugin
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M4</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>3.0.0-M4</version> </dependency> </dependencies> </plugin>
POM.xml
<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>com.testingdocs.sample</groupId> <artifactId>Sample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Sample</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M4</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>3.0.0-M4</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
Maven Build
Run As >> Maven Build
Add Maven goals like clean install
The JUnit Calculator tests will run as part of the Maven build process.