Scalatest: Add support for JUnit5 and provide a solution for JUnitRunner as an Extension

Created on 19 Dec 2018  路  3Comments  路  Source: scalatest/scalatest

In JUnit5 the @RunWith annotated classes need to now use the @ExtendWith annotation, which, in term, is no longer using a Runner, but and Extension. Hence, the code will have to be re-worked a bit in order to support JUnit5.

Most helpful comment

@mfulgo, In the meantime you can use scalatest-junit-runner which is a simple TestEngine implementation to run Scalatest suites with the JUnitPlatform in Gradle.

All 3 comments

As a stopgap solution, you can run your existing ScalaTest using the Platform engine by replacing the JUnit Runner class with JUnitPlatform class.

i.e. replace import:
org.scalatest.junit.JUnitRunner
with:
org.junit.platform.runner.JUnitPlatform

replacing the annotation @RunWith(classOf[JUnitRunner]) becomes @RunWith(classOf[JUnitPlatform])

replace Junit4 dependency in your [sbt / Gradle / Maven] build script with

Junit4

`package io.truthencode.example.junit4

import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.{FunSpec, Matchers}

@RunWith(classOf[JUnitRunner])
class JUnitExampleTest extends FunSpec with Matchers {
describe("ScalaTest with JUnit4") {

it("should pass this test") {
 1 should equal(2 - 1)
}

it("should fail here") {
  1 should equal(45)
}

}
}`

Becomes

JUnit 5

`package io.truthencode.example.junit5

import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.scalatest.{FunSpec, Matchers}

@RunWith(classOf[JUnitPlatform])
class JUnitExampleTest extends FunSpec with Matchers {
describe("ScalaTest with JUnit5") {

it("should pass this test") {
 1 should equal(2 - 1)
}

it("should fail here") {
  1 should equal(45)
}

}
}`

YMMV based on build tool and IDE. I tend to use Gradle in IDEA and have noticed the Test results window shows 'classMethod' instead of the Descriptions Using FunSpc but at least once again captures the results and I can include JUnit 5, ScalaTest and Concordion Acceptance tests in the same build.
image

I would at some point love to have my ScalaTests take advantage of JUnit5 Extensions.

In contrast to @adarro, attempting to use JUnitPlatform didn't work when running tests from gradle. I had some success with this by using the junit-vintage runner and keeping the @RunWith(classOf[JUnitRunner]).

Digging into it a bit, I think the most correct thing to do is to create a TestEngine for Scalatest, rather than an Extension. See https://junit.org/junit5/docs/current/user-guide/#launcher-api. It would probably go into a scalatestplus library, given the modular design of 3.x.

@mfulgo, In the meantime you can use scalatest-junit-runner which is a simple TestEngine implementation to run Scalatest suites with the JUnitPlatform in Gradle.

Was this page helpful?
0 / 5 - 0 ratings