JUnit Test with Maven in VSCode
Install VSCode
Setup here: https://code.visualstudio.com/docs/setup/setup-overview
Install and create a Maven project
Full Installation Guide here: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
If you have Maven installed, follow these steps:
Generate the project
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
Change into project directory
cd my-app
Build the project
mvn package
Test and compile the project
java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App
You should get an output with:
Hello World!
Modify our project
Let’s start creating simple math functions
Search for App.java
file and replace the contents with this code:
Search for AppTest.java
and replace the contents with this code:
You can keep creating tests such as:
@Test
public void multiply_FiftyTimesTwo_ReturnsOneHundred()
{
// Arrange
final int expected = 100;
// Act
final int actual = App.multiply(50, 2);
// Assert
Assert.assertEquals(actual, expected);
}
Build the project
mvn package
Output:
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.mycompany.app.AppTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.026 s - in com.mycompany.app.AppTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
Test and compile the project
java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App
Output:
6
Hello World!
An alternative way to run tests is by click Run Test inside AppTest.java
In the example below, Run Test is located just below code line 44.
View Tests and Test Report
Migrating JUnit 4 to JUnit 5
Change your pom.xml
dependencies to:
Change your AppTest.java
into:
Adding test coverage
Check the test coverage report
In the VSCode open the Extension MarketPlace and search Coverage Gutters
Click install button
Open the pom.xml file under your root folder and replace the content with http://bit.ly/2Df1Oj2 to add one plugin support.
Open the terminal in the VSCode and run
mvn installmvn clean jacoco:prepare-agent install jacoco:report
Open your App.java
file under main/java/com/mycompany/app
folder and click the Watch button to check the report
Red bar: test code is not covered
Yellow bar: condition is not covered
Green bar: code is covered
Open the index.html
file under your root folder/target/site/jacoco.
To open:
Then paste (Ctrl and V for Windows, Command and V for MacOS) the path in your browser.
You can see a very detailed test coverage report:
Thanks for reading! =)
Want to learn the different types of software testing? https://medium.com/@clarkjasonngo/easy-examples-for-black-white-and-gray-box-testings-fdceb2a8b664
Test Coverage section contributor: