JUnit 5用于Android测试

29
如何配置 JUnit 5 进行 Android 单元测试?我尝试过:
testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0")

但是当我运行之前最简单的单元测试时,它不起作用:

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

我收到一个错误信息:

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.

相关帖子:如何在Gradle中使用JUnit 5? - Mahozad
5个回答

33

关于JUnit 5在Android上的支持,请参考此问题此问题

将以下构建脚本依赖项添加到您的顶级 build.gradle[.kts]文件中:

buildscript {
  dependencies {
    classpath("de.mannodermaus.gradle.plugins:android-junit5:1.8.2.1")
  }
}

在你的应用或库build.gradle[.kts]文件中添加以下代码:

plugins {
  // ...
  id("de.mannodermaus.android-junit5")
}

dependencies {
  // Aggregator dependency on JUnit api, engine, and params
  testImplementation("org.junit.jupiter:junit-jupiter:5.9.1")
  // (Optional) If you also have JUnit 4-based tests
  testImplementation("junit:junit:4.13.2")
  testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.9.1")
}

如果您使用Android Gradle插件3.2.0或更高版本Gradle 4.7或更高版本,则可以使用上述解决方案。有关更多信息,请参阅插件GitHub页面

扩展答案

如果您想在仪器化测试(androidTest源集)中使用JUnit 5,请执行以下操作:

  1. 将这些依赖项添加到您的应用程序或库构建脚本中:
androidTestImplementation("de.mannodermaus.junit5:android-test-core:1.3.0")
androidTestRuntimeOnly("de.mannodermaus.junit5:android-test-runner:1.3.0")
  1. 在您的测试类中,使用ActivityScenarioExtension代替ActivityScenarioRule
import de.mannodermaus.junit5.ActivityScenarioExtension

class MyActivityTest {

  @JvmField
  @RegisterExtension
  val scenarioExtension = ActivityScenarioExtension.launch<MyActivity>()

  @Test
  fun test1() {
    val scenario = scenarioExtension.scenario
    scenario.moveToState(Lifecycle.State.RESUMED)
    assertThat(scenario.state).isEqualTo(Lifecycle.State.RESUMED)
  }

  @Test
  fun test2(scenario: ActivityScenario<MyActivity>) {
    scenario.moveToState(Lifecycle.State.RESUMED)
    assertThat(scenario.state).isEqualTo(Lifecycle.State.RESUMED)
  }
}

4

Android Studio基于IDEA,对吗?

那么请看这里的答案https://dev59.com/o6Xja4cB1Zd3GeqPLxQs#46161799或者直接阅读用户指南http://junit.org/junit5/docs/current/user-guide/#running-tests-ide-intellij-idea

总结:

// Only needed to run tests in an IntelliJ IDEA that bundles an older version
testImplementation("org.junit.platform:junit-platform-launcher:1.0.0")
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.0.0")
testImplementation("org.junit.vintage:junit-vintage-engine:4.12.0")

我还没有尝试过这个项目,但它可以帮助你在Android上使用JUnit 5: https://github.com/aurae/android-junit5


3
现在是2023年1月,以前能用的答案在Android Studio 2021.3.1(补丁1)和运行Gradle 7.4上对我不起作用。
以下是我所做的使它工作的步骤:
首先,尝试按照@Mahozad的答案进行操作。我选择它是因为它提到了最新的junit-jupiter:5.9.1版本
但是我的应用程序的build.gradle不喜欢那里的plugins {...}部分,所以我改用了@BoonKeatTeo的文章中的apply plugin: 'de.mannodermaus.android-junit5'
仍然无法识别任何导入的符号,因此我添加了@DagnogoJean-François的答案中的存储库URL(文件>设置>构建...>远程Jar存储库)。
它继续抱怨在测试类中添加了import static org.junit.jupiter.api.Assertions.*;,在从命令行运行gradlew build --warning-mode=all之后,我意识到删除已弃用的jcenter存储库是个好主意。除了通过设置删除它外,我还在根build.gradle中将所有jcenter()出现替换为mavenCentral()
我仍然有导入警告,因此我决定删除所有导入并接受Android Studio的建议添加org.junit.jupiter:junit-jupiter:5.8.1依赖项。这似乎已经解决了问题,现在我的测试类符号上没有任何警告。
总结一下,这是我的 build.gradle 文件现在的样子:
apply plugin: 'com.android.library'
apply plugin: 'de.mannodermaus.android-junit5'

android {
    compileSdkVersion 33
    buildToolsVersion "33.0.1"
    compileOptions.encoding = 'windows-1251'
    useLibrary 'org.apache.http.legacy'
    namespace 'com.susu.mylib'

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 33
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles 'proguard.cfg'
        }
    }

    testOptions {
        unitTests.all {
            useJUnitPlatform()
        }
    }
}

dependencies {
    implementation "androidx.core:core-ktx:1.9.0"
    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    implementation "com.android.billingclient:billing:5.1.0"

    implementation 'org.junit.jupiter:junit-jupiter:5.8.1'
}

非常欢迎对如何进一步改进此事项进行评论。

3

您可以通过将以下内容添加到gradle文件中来使用官方版本:

android {
    testOptions {
        unitTests.all {
            useJUnitPlatform()
    }
  }
}



dependencies {
     testImplementation "org.junit.jupiter:junit-jupiter:5.8.0"
}

为了能够在JUnit5的同时运行您的JUnit4测试,请添加:

testImplementation "org.junit.vintage:junit-vintage-engine:5.8.0"

2

始终使用官方版本

首先,请前往此处的Junit官方文档https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api。您将看到所有最新版本,如下所示:enter image description here

然后,在您的应用程序/gradle中添加此依赖项:

testImplementation('org.junit.jupiter:junit-jupiter:X.X.X')

其中X.X.X是您想要的版本号。例如在我的情况下,它是

testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')


1
我同意你的看法,但是官方版本无法与测试工具一起正常工作。如果你加上androidTestImplementation('org.junit.jupiter:junit-jupiter:X.X.X'),就会遇到一些错误。 - Ali Doran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接