Jupiter tests in JUnit 4

JUnit 5 has been designed to be forward and backward compatible. On the one hand, the Vintage component supports running legacy code on JUnit 3 and 4. On the other hand, JUnit 5 provides a JUnit 4 runner that allows to run JUnit 5 in IDEs and build systems that support JUnit 4, but does not yet support the new JUnit Platform 5 directly.

Let's see one example. Imagine we want to run a Jupiter test in an IDE does not support JUnit 5, for example, an old version of Eclipse. In this case, we need to annotate our Jupiter test with @RunWith(JUnitPlatform.class). The JUnitPlatform runner is a JUnit 4-based runner, which enables to run any test whose programming model is supported on the JUnit Platform in a JUnit 4 environment. Therefore, our test would result as follows:

package io.github.bonigarcia;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
public class JUnit5CompatibleTest {

@Test
void myTest() {
String message = "1+1 should be equal to 2";
System.out.println(message);
assertEquals(2, 1 + 1, message);
}

}

If this test is contained in a Maven project, our pom.xml should contain the following dependencies:

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

On the other hand, for a Gradle project, our build.gradle is the following:

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.junit.platform:junit-platform-gradle-plugin:${junitPlatformVersion}")
}
}

repositories {
mavenCentral()
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.junit.platform.gradle.plugin'

compileTestJava {
sourceCompatibility = 1.8
targetCompatibility = 1.8
options.compilerArgs += '-parameters'
}

dependencies {
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
testCompile("org.junit.platform:junit-platform-runner:${junitPlatformVersion}")
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.159.178