JUnit 5 for Android testing

mac229 picture mac229 · Sep 11, 2017 · Viewed 9.7k times · Source

How to configure JUnit 5 for Android unit testing? I tried:

testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0")

But it doesn't work, when I run previous the simplest unit test:

@Test
public void addition_isCorrect() throws Exception {
    assertEquals(4, 2 + 2);
}

I get error:

Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
    at org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry.loadTestEngines(ServiceLoaderTestEngineRegistry.java:31)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:42)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:36)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1
Empty test suite.

Answer

Mahozad picture Mahozad · Dec 7, 2018

Add this buildscript dependency in your top-level build.gradle file:

buildscript {
  dependencies {
    classpath "de.mannodermaus.gradle.plugins:android-junit5:1.3.1.1"
  }
}

And add these lines in your app build.gradle file:

apply plugin: "de.mannodermaus.android-junit5"

dependencies {
  // (Required) Writing and executing Unit Tests on the JUnit Platform
  testImplementation "org.junit.jupiter:junit-jupiter-api:5.3.1"
  testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.3.1"

  // (Optional) If you need "Parameterized Tests"
  testImplementation "org.junit.jupiter:junit-jupiter-params:5.3.1"

  // (Optional) If you also have JUnit 4-based tests
  testImplementation "junit:junit:4.12"
  testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.3.1"
}

You can use the above solution if you are using Android Gradle plugin 3.2.0 or higher and Gradle 4.7 or higher. For more information about instrumentation test support and minimum required SDK versions refere to its Github page.