JUnit4 Testing in VS-Code


Create the Hello World project here

Add the Junit 4 Dependencies

Add the Junit 4 dependencies to the pom.xml

<?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>com.skills421.examples</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.13.2</junit.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>

Create a new Package in src/test

  • right click java in test/java
  • New Folder
  • enter: com/skills421/examples

Create a new test class in com.skills421.examples

  • Right click examples
  • New File
  • CounterTest.java

Add the following code to CounterTest.java

package com.skills421.examples;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CounterTest {

@Test
public void additionTest() {
int count = 1;
count++;

assertEquals(2, count);
}
}

Run the Tests

Right click the symbol to the left of the class or the function definition to run all the tests in the class or a specific test.

Leave a comment