如何从 Android 应用程序代码 (MainActivity) 中运行/调用插桩测试

问题描述 投票:0回答:0

在目前的安排中,在Android上,可以通过以下方法调用Instrumented Tests:

  1. 在 Android Studio 中 -> 右键单击保存在“androidTest”下的类
  2. 在 CMD 提示符下启动命令
    adb shell am instrument -w com.example.testing/androidx.test.runner.AndroidJUnitRunner

但是我的是独特的要求。根据我的要求,我想从 App 代码本身的 UI 运行/调用相同的测试用例(写在保存在 androidTest 下的类中),即当用户单击 UI 上显示的按钮时,相应的测试用例被执行。

以下是保存在“androidTest”文件夹下的“ExampleInstrumentedTest”中编写的代码。

package com.example.myapplication

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.uiautomator.UiDevice

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    fun testCaseForButton1() {
        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
        //Filler step
        assertEquals("com.example.myapplication", appContext.packageName)
    }

    @Test
    fun testCaseForButton2() {
        val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
        //Filler step
        assertEquals("com.sec.android.app.launcher", device.launcherPackageName)
    }
}

MainActivity() 中的代码:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.buttonRunTest1)
            .setOnClickListener {
                //Invoke testCaseForButton1
            }

        findViewById<Button>(R.id.buttonRunTest2)
            .setOnClickListener {
                //Invoke testCaseForButton2
            }
    }

我在某处读到,无法从 App 代码中调用/触发“仪器化”测试。也尝试过但失败并出现错误“没有注册仪器!必须在注册仪器下运行”

请求有关要在“OnClickListener”中编写的代码的帮助。

尝试了几种方法:

// Code to execute when the button is clicked
fun startTest(){
   val packageName = "com.example.myapplication"
   val testRunnerClass = "androidx.test.runner.AndroidJUnitRunner"
   val command = "am instrument -w $packageName/$testRunnerClass"
   Runtime.getRuntime().exec(command)
}
// Code to execute when the button is clicked
fun startTest(){
   val instrumentation = InstrumentationRegistry.getInstrumentation()
   val paramTypes = arrayOf(ComponentName::class.java, Bundle::class.java)
   val method = instrumentation.javaClass.getDeclaredMethod("startInstrumentation", *paramTypes)
}

但是没有任何效果。理想情况下,他们应该开始检测测试用例。

android ui-automation instrumented-test
© www.soinside.com 2019 - 2024. All rights reserved.