首页 > 解决方案 > AndroidJUnit4 应该有一个公共构造函数

问题描述

我正在尝试按照 Android Developer Docs 编写仪表化单元测试,但是,当然,它不起作用。我收到错误消息:

Custom runner class AndroidJUnit4 should have a public constructor with signature AndroidJUnit4(Class testClass)

当我运行我的示例测试时:

package com.devetry.ytp

import android.content.Context
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

import androidx.test.runner.AndroidJUnitRunner
import org.junit.Assert
import org.junit.Rule

@RunWith(AndroidJUnit4::class)
class ExampleAndroidTest {

    /**
     * VARIABLES
     */



    /**
     * LIFE CYCLE
     */


    /**
     * Example Android Test
     *
     * An example android test
     */
    @Test
    fun exampleAndroidTest() {
        val context = InstrumentationRegistry.getTargetContext()
        Assert.assertEquals("com.devetry.ytp", context.packageName)
    }

}

我已经尝试了多种解决方案来解决我在网上发现的这个特定错误,但就像大多数 Android 设备一样,解决方案要么已经过时,要么根本不起作用。不幸的是,在所有解决方案中,我什至无法识别一个共同的主题,从而使我陷入困境。

如何解决错误并让仪器化单元测试运行?

标签: androidandroid-testingandroid-instrumentation

解决方案


package com.devetry.ytp

import android.content.Context
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

// AndroidJunitRunner and AndroidJUnit4 are not from the same pacakge
import androidx.test.runner.AndroidJUnitRunner
import org.junit.Assert
import org.junit.Rule

@RunWith(AndroidJUnit4::class)
class ExampleAndroidTest {

    /**
     * VARIABLES
     */



    /**
     * LIFE CYCLE
     */
...
}

您没有使用同一个包中的类,请确保它们是一致的。支持测试包与 androidx 包冲突。


推荐阅读