我正在将我的应用程序迁移到 androidx,我似乎无法让我的单元测试工作.我从 Google’s AndroidJunitRunnerSample中获取了示例,该示例已更新为使用新的androidx api.尝试运行测试时出现以下错误:
java.lang.Exception: Delegate runner 'androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner' for AndroidJUnit4 could not be loaded. Check your build configuration.
这是我的模块build.gradle:
android {
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
// Test dependencies
androidTestImplementation 'androidx.test:core:1.0.0-beta02'
androidTestImplementation 'androidx.test.ext:junit:1.0.0-beta02'
androidTestImplementation 'androidx.test:runner:1.1.0-beta02'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-beta02'
androidTestImplementation "androidx.arch.core:core-testing:2.0.0"
androidTestImplementation 'androidx.room:room-testing:2.1.0-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-beta02'
androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
}
以下是我的测试结构:
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.ext.junit.runners.AndroidJUnit4;
@RunWith(AndroidJUnit4.class)
public class EntityParcelTest {
@BeforeClass
public void createEntities() {
// Setup...
}
@Test
void someTest() {
// Testing here
}
我究竟做错了什么?
从测试类中删除@RunWith(AndroidJUnit4.class)注释修复了这个问题,虽然我无法真正说出为什么或如何修复它.编辑:好吧我做了一些测试.我将我的应用程序迁移到Kotlin,突然我注意到测试也开始使用@RunWith注释了.这是我发现的:
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.ext.junit.runners.AndroidJUnit4;
@RunWith(AndroidJUnit4.class) // <-- @RunWith + @BeforeClass = Error
public class AndroidXJunitTestJava {
@BeforeClass
public static void setup() {
// Setting up once before all tests
}
@Test
public void testing() {
// Testing....
}
}
此java测试失败,无法加载AndroidJunit4的Delegate运行程序错误.但是如果我删除了@RunWith注释,它就可以了.另外,如果我用@Before替换@BeforeClass设置,如下所示:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.ext.junit.runners.AndroidJUnit4;
@RunWith(AndroidJUnit4.class) // <-- @RunWith + @Before = works?
public class AndroidXJunitTestJava {
@Before
public void setup() {
// Setting up before every test
}
@Test
public void testing() {
// Testing....
}
}
测试将运行没有错误.我需要使用@BeforeClass注释,所以我刚刚删除了@RunWith.
但是现在我正在使用Kotlin,以下(应该等于第一个java示例)可以工作:
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AndroidXJunitTest {
companion object {
@BeforeClass fun setup() {
// Setting up
}
}
@Test
fun testing() {
// Testing...
}
}
另外,正如Alessandro Biessek在答案和@Ioane Sharvadze的评论中所说的那样,@ Rule注释也会出现同样的错误.如果我添加一行
@Rule val instantTaskExecutorRule = InstantTaskExecutorRule()
对于Kotlin示例,发生了相同的委托运行程序错误.必须替换为
@get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule()
说明here.
