【发布时间】:2020-10-14 20:35:55
【问题描述】:
有没有办法在单元测试期间访问资源?我尝试了 StackOverflow 中的许多可能性,但都失败了。
我最后一次尝试(匹配下面的代码)给我这个任务testReleaseUnitTest的错误:
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)
at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)
at fr.alpha.calculator.TestOperationManager.testAddCharacterEmptyOperation(TestOperationManager.java:20)
仪器是通过仪器测试创建的,对吗?是否有可能避免这种情况以使测试更快?
感谢阅读!
我的测试课:
package fr.alpha.calculator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.Test;
import android.content.Context;
import android.content.res.Resources;
import androidx.test.core.app.ApplicationProvider;
import fr.alpha.calculator.OperationManager;
public class TestOperationManager{
@Test
public void testAddCharacterEmptyOperation(){
final Context context = ApplicationProvider.getApplicationContext();
final Resources res = context.getResources();
final OperationManager testOperationManager = new OperationManager(res);
assertTrue(testOperationManager.addCharacter('0'),
"addCharacter must return true !");
final OperationManager expectedOperationManager =
new OperationManager(res);
expectedOperationManager.setOperation("0");
assertEquals(expectedOperationManager, testOperationManager,
"operation must be equal to \"0\" !");
}
}
我的app/build.gradle 文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "fr.alpha.calculator"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions{
unitTests.all{
useJUnitPlatform()
}
}
}
dependencies {
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.gridlayout:gridlayout:1.0.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'org.apache.commons:commons-lang3:3.10'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2'
testImplementation 'androidx.test:core:1.2.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.2'
}
【问题讨论】:
标签: android unit-testing junit junit5