如何在本地单元测试期间访问资源?



有没有办法在单元测试期间访问资源?我尝试了在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'
}

我认为这不是一个很好的解决方案,但我没有使用资源来获取我想要的字符串,而是简单地将其放在测试类的字符串变量中。我希望有人有更好的答案,我的哈哈

最新更新