我正在尝试使用AndroidJunit4测试RecyclerView,这是我的测试代码:
package com.kaushik.myredmart.ui;
// all includes
@RunWith(AndroidJUnit4.class)
public class ProductListActivityTest {
@Rule
public ActivityTestRule<ProductListActivity> rule = new ActivityTestRule<>(ProductListActivity.class);
@Test
public void ensureListViewIsPresent() throws Exception {
ProductListActivity activity = rule.getActivity();
View viewByIdw = activity.findViewById(R.id.productListView);
assertThat(viewByIdw,notNullValue());
assertThat(viewByIdw, instanceOf(RecyclerView.class));
RecyclerView productRecyclerView = (RecyclerView) viewByIdw;
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
assertThat(adapter, instanceOf(ProductAdapter.class));
}
}
Run Code Online (Sandbox Code Playgroud)
我正面临检查适配器的问题.虽然productRecyclerView传递非null测试和RecyclerView的实例,但它在最后一行中跟随错误:
java.lang.AssertionError:
Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter
but: null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at com.kaushik.myredmart.ui.ProductListActivityTest.ensureListViewIsPresent(ProductListActivityTest.java:45)
Run Code Online (Sandbox Code Playgroud)
代码中有什么问题?
java android recycler-adapter android-recyclerview android-junit
我在我的项目中使用了 AndroidJUnitRunner,但是单元测试在 Android Studio 和命令行中通过gradlew.
我正在使用这个开源项目的主分支 OneBusAway(截至本次提交):https : //github.com/OneBusAway/onebusaway-android
我看到所有 142 个测试的执行时间在实际运行时间中超过 3 分钟,但 Android 在它显示在“测试结果”下的执行时间中只注册了其中的一小部分。在切换到 AndroidJUnitRunner 之前,所有这些单元测试都在 20 秒内一致地执行。
下面是一个示例测试:
/**
* Tests to evaluate utility methods related to math conversions
*/
@RunWith(AndroidJUnit4.class)
public class MathUtilTest {
@Test
public void testOrientationToDirection() {
// East
double direction = MathUtils.toDirection(0);
assertEquals(90.0, direction);
}
}
Run Code Online (Sandbox Code Playgroud)
这是build.gradle配置:
android {
dexOptions {
preDexLibraries true
}
compileSdkVersion this.ext.compileSdkVersion
buildToolsVersion "27.0.3"
defaultConfig {
minSdkVersion 14
targetSdkVersion 21
versionCode 93 …Run Code Online (Sandbox Code Playgroud) android android-testing android-studio android-gradle-plugin android-junit
我正在处理一个多模块项目,在从支持库转换到 AndroidX 后,./gradlew connectedCheck失败了:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':MyProject:connectedDebugAndroidTest'.
> There were failing tests. See the report at: file:///Users/justinpollard/Dev/android-app/MyProject/build/reports/androidTests/connected/index.html
Run Code Online (Sandbox Code Playgroud)
再往上一点,我看到这条消息:
11:48:13 I/RemoteAndroidTest: Running am instrument -w -r com.myproject.test/androidx.test.runner.AndroidJUnitRunner on Pixel XL - 9
11:48:13 V/ddms: execute: running am instrument -w -r com.myproject.test/androidx.test.runner.AndroidJUnitRunner
11:48:15 V/InstrumentationResultParser: INSTRUMENTATION_RESULT: shortMsg=Process crashed.
11:48:15 I/InstrumentationResultParser: test run failed: 'Instrumentation run failed due to 'Process crashed.''
Starting 0 tests on Pixel XL - 9
Tests …Run Code Online (Sandbox Code Playgroud) 我在 Android 中尝试使用 FragmentScenario 时遇到此错误
error: package androidx.fragment.app.testing does not exist
import androidx.fragment.app.testing.FragmentScenario;
^
Run Code Online (Sandbox Code Playgroud)
这是我的简单单元测试示例:
package com.example.myapplication;
import androidx.fragment.app.testing.FragmentScenario;
import android.os.Build;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@RunWith(AndroidJUnit4.class)
@Config(manifest = Config.NONE, sdk = Build.VERSION_CODES.P)
public class MainActivityTest {
@Test
public void testFragmentScenario() {
FragmentScenario<BlankFragment> scenario = FragmentScenario.launchInContainer(BlankFragment.class);
}
}
Run Code Online (Sandbox Code Playgroud)
构建.gradle(应用程序):
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
def test_version = '1.2.0'
def fragment_version = …Run Code Online (Sandbox Code Playgroud) 我有以下测试,其中测试名称带有空格和反引号用于我的仪器测试
@RunWith(AndroidJUnit4::class)
class MyTestClass {
@Rule
@JvmField
var activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
@Test
fun `My space name testing`() {
// Some test
}
}
Run Code Online (Sandbox Code Playgroud)
但是在运行的时候,却无法执行(即No test was found)
检查它,我在测试函数名称上看到了这个 linting 错误..
This inspection reports identifiers in android projects which are not accepted by the Android runtime (for example, method names containing spaces)
当我将测试函数从My space name testingto重命名时mySpaceNameTesting,测试运行。
AndroidJunit4 运行时真的不支持带空格的测试函数名吗?
android kotlin android-instrumentation android-runtime android-junit
我正在尝试使用 MockitoJUnitRunner 运行单元测试;它们在 Android Studio 下运行良好,但一些(不是全部)测试在命令行中运行时失败 - 这是一个大问题,我需要能够从我的持续集成平台运行它们,而不仅仅是从 IDE 运行它们。这是正在测试的实际方法之一:
internal fun requestSecurityQuestion() {
if (isViewAttached) mvpView.showLoadingDialog()
api.getSecurityQuestionToday(mDataManager.token,
ACTION_ASK_SECURITY_QUESTION_ON_LOGIN, 0)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : CallbackWrapper<SettingsResponse>(mDataManager) {
override fun onSuccess(response: SettingsResponse) {
mDataManager.securityQuestion = response.question
mDataManager.processId = response.processId
if (isViewAttached) {
mvpView.dismissLoadingDialog()
mvpView.showVsecVerificationDialog(0, response.question!!)
}
}
override fun onFailed(errorId: Int, jsonResponse: String?) {
if (isViewAttached) mvpView.dismissLoadingDialog()
}
})
}
Run Code Online (Sandbox Code Playgroud)
这是失败的测试之一:
@RunWith(MockitoJUnitRunner::class)
class HomePresenterTest {
@Mock
private var mView: HomeView? = null
@Mock
private var mDataManager: DataManager? = null
@Mock
private var …Run Code Online (Sandbox Code Playgroud) 我kotlin collections library (listOf, first, toList, etc,..在我们的AndroidTest包中使用) 方法来运行 UI 测试,AndroidJunit4 runner并且在我提到 kotlin 集合库的任何地方都会遇到这些类型的错误。
java.lang.NoSuchMethodError: No static method listOf(Ljava/lang/Object;)Ljava/util/List; in class Lk/v/i; or its super classes (declaration of 'k.v.i' appears
Run Code Online (Sandbox Code Playgroud)
奇怪的是我在编译时没有看到任何问题,也没有在类级别独立运行测试时看到任何问题。仅当我使用 Gradle 运行整个测试套件时才会出现此问题
这是我用来使用 Gradle 运行 UI 测试套件的命令
./gradlew connectedCheck --info --full-stacktrace --no-build-cache --debug
Run Code Online (Sandbox Code Playgroud)
我怀疑在运行时加载的类似乎与编译时不同
这是build.gradle依赖项
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.71"
// Instrumented Tests
testImplementation "androidx.test:core:1.2.0"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Run Code Online (Sandbox Code Playgroud) android kotlin android-uiautomator android-junit androidjunitrunner
我使用 Android Studio 4.2.2 中的记录器记录了一个 Espresso 测试,其中包括一个断言,即我的 MainActivity UI 上的文本字段显示了正确的文本字符串。然后我将其保存到 SplashActivityTest.java:
公共类 SplashActivityTest {
@Rule
public ActivityTestRule<SplashActivity> mActivityTestRule = new ActivityTestRule<>(SplashActivity.class);
@Before
public void registerIdlingResource() {
IdlingRegistry.getInstance().register(CountingIdlingResourceSingleton.espressoIdlingResource);
}
@After
public void unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(CountingIdlingResourceSingleton.espressoIdlingResource);
}
@Test
public void splashActivityTest() {
ViewInteraction textView = onView(
allOf(withId(R.id.playlistText), withText("My Playlists"),
withParent(withParent(withId(R.id.nav_host_fragment))),
isDisplayed()));
textView.check(matches(isDisplayed()));
ViewInteraction textView2 = onView(
allOf(withId(R.id.playlistText), withText("My Playlists"),
withParent(withParent(withId(R.id.nav_host_fragment))),
isDisplayed()));
textView2.check(matches(withText("My Playlists")));
}
Run Code Online (Sandbox Code Playgroud)
}
我向此类添加了 Idling 注册表的使用,因为在我的应用程序中,实际发生的启动画面是启动器活动,然后启动加载我想要测试的 UI 的活动。
我有这个代码:
// Necessary for automated tests, decrement handled in MainActivity.onResume()
CountingIdlingResourceSingleton.increment();
Run Code Online (Sandbox Code Playgroud)
在 …
automated-tests android-espresso android-junit android-espresso-recorder
我像这样注释了我的课程
\n\n@RunWith(AndroidJUnit4.class)\npublic class WorkdayProviderTest\nRun Code Online (Sandbox Code Playgroud)\n\n此外,还注释了我的测试方法
\n\n@Test\npublic void insert_dataInsertsCorrectly()\nRun Code Online (Sandbox Code Playgroud)\n\n最后,像这样配置我的 build.gradle defaultConfig 和依赖项
\n\ndefaultConfig {\n applicationId \'com.jueggs.workinghours\'\n minSdkVersion 16\n targetSdkVersion 23\n versionCode 1\n versionName "1.0"\n\n testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"\n}\n\nandroidTestCompile "junit:junit:4.12"\nandroidTestCompile "com.android.support:support-annotations:23.3.0"\nandroidTestCompile "com.android.support.test:runner:0.4.1"\nandroidTestCompile "com.android.support.test:rules:0.4.1"\nandroidTestCompile "com.android.support.test.espresso:espresso-core:2.2.1"\nandroidTestCompile "com.android.support.test.espresso:espresso-contrib:2.2.1"\nandroidTestCompile "org.hamcrest:hamcrest-library:1.3"\nRun Code Online (Sandbox Code Playgroud)\n\n并像这样配置测试运行
\n\n\n\n它\xc2\xb4s告诉我
\n\nNo tests were found\n\nTest running failed: Instrumentation run failed due to \'java.lang.ClassNotFoundException\'\nRun Code Online (Sandbox Code Playgroud)\n\n如何解决这个问题?
\n设置:
我继承的一个较旧的项目有很多遗留的仪器测试,我想对它们施加超时,因为它们中的很多都可以无限期地挂起,这使得很难获得测试报告。我正在将测试更新为 Junit4 样式,但目前它们都在扩展 ActivityInstrumentationTestCase2。
到目前为止尝试过:
在AndroidJUnitRunner的文档中,它说要设置这个标志:
设置将应用于每个测试的超时(以毫秒为单位):-e timeout_msec 5000 ...
...所有参数也可以通过元数据标签在 AndroidManifest 中指定
我已经尝试将 AndroidJUnitRunner 配置添加到应用程序清单和测试清单,但 timeout_msec 元数据项到目前为止没有任何影响。