【问题标题】:Start Activity for testing启动 Activity 进行测试
【发布时间】:2015-05-12 13:01:53
【问题描述】:

我有一个使用 Realm db 的测验应用程序。每次用户选择一个答案时,她都会单击一个按钮,然后会出现新的问题文本。 就是这样,直到她到达终点,我开始一个新的 Activity 并根据正确答案显示分数。

我应该如何开始/测试(我猜是 Espresso)该活动,而不必每次所有答案都手动输入,并在每个答案后单击按钮,直到我到达最后一个? p>

我需要将一些模拟数据传递给一个变量并创建一个 Intent,但我不知道如何在 Espresso 中找到与此相关的任何内容

【问题讨论】:

  • 如果您将该 Activity 作为启动器 Activity 以使该 Activity 成为您的应用显示的第一个 Activity 会怎样?
  • 嗯我猜它可能是这样的,但我不确定这是否是一个“好”的做法,是否允许我改变我的 src 文件结构只是为了测试。
  • 这是您的应用程序。你正在测试它。您可以仅出于测试目的更改 src 文件,然后再恢复。
  • 这就像说我不会检查我的网站是否防黑客,因为黑客很糟糕。
  • 呵呵 :) 好的,你是对的。我认为问题在于每次更改代码时都必须这样做 - 我在想也许使用某些框架我不必更改代码中的某些内容。

标签: android android-testing android-espresso


【解决方案1】:

您可以使用如下自定义意图启动您的下一个活动:

@RunWith(AndroidJUnit4.class)
public class NextActivityTest {

  @Rule
  public ActivityTestRule<NextActivity> activityRule 
     = new ActivityTestRule<>(
        NextActivity.class,
        true,     // initialTouchMode
        false);   // launchActivity. False to customize the intent

  @Test
  public void intent() {
    Intent intent = new Intent();
    intent.putExtra("your_key", "your_value");

    activityRule.launchActivity(intent);

    // Continue with your test
  }
}

完整示例:https://github.com/chiuki/android-test-demo

博文:http://blog.sqisland.com/2015/04/espresso-21-activitytestrule.html

【讨论】:

  • 我可以将它与 UiAutomator 一起使用以测试我的通知吗?
  • @chiuki 我正在尝试相同的代码,它显示为绿色,但是当我添加 intended(hasComponent(NextActivity.class.getName())); 时,我得到了NullPointerException: Attempt to invoke virtual method 'void android.support.test.espresso.intent.Intents.internalIntended(org.hamcrest.Matcher, android.support.test.espresso.intent.VerificationMode, java.util.List)' on a null object reference
  • ActivityTestRule 已被弃用,这个 Kotlin 示例可能会有所帮助:stackoverflow.com/a/67929217/3692788
【解决方案2】:

对于使用 AndroidX 进行测试的开发者来说,情况有所改变。

这是一个示例 UI 测试用例,用于测试我的预期活动是否在单击文本视图后打开。

import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.softway.dhananjay.tournamentapp.tournament.TournamentActivity
import org.junit.Test

class MainActivityTest {

    @Test
    fun tournament_activity_starts_onClick_of_textView() {

        Intents.init()

        val activityScenario: ActivityScenario<MainActivity> =
            ActivityScenario.launch(MainActivity::class.java)


        activityScenario.moveToState(Lifecycle.State.RESUMED)

        onView(withId(R.id.startTextView)).perform(ViewActions.click())

        intended(hasComponent(TournamentActivity::class.java.name))

        Intents.release()

        activityScenario.moveToState(Lifecycle.State.DESTROYED)

    }
}

【讨论】:

    【解决方案3】:

    首先,看到这个问题:Android Monkey Runner

    然后你可以看到这些指南:Monkey Runner

    它使您可以使用 Python 在源代码之外测试您的 android 活动。因此,您可以像这样触发事物并进入特定活动:

    #! /usr/bin/env monkeyrunner
    
    from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
    from random import randint
    
    print "get device"
    device = MonkeyRunner.waitForConnection()
    package = 'my.packaget'
    activity = 'my.package.activity'
    runComponent = package + '/' + activity
    device.startActivity(component=runComponent)
    
    #use commands like device.touch and device.drag to simulate a navigation and open my activity
    
    #with your activity opened start your monkey test
    print "start monkey test"
    for i in range(1, 1000):
        #here i go emulate only simple touchs, but i can emulate swiper keyevents and more... :D
        device.touch(randint(0, 1000), randint(0, 800), 'DOWN_AND_UP')
    
    print "end monkey test"
    

    保存然后运行:monkeyrunner test.py

    【讨论】:

    • 感谢您的链接。我一定会检查并报告。
    【解决方案4】:
    private void launchApp(){
            // Launch the app
            Context context = InstrumentationRegistry.getContext();
            final Intent intent = context.getPackageManager()
                    .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
            // Clear out any previous instances
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intent);
    
            // Wait for the app to appear
            device.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
                    LAUNCH_TIMEOUT);
        }
    

    【讨论】:

      【解决方案5】:

      您可以使用以下代码使用意图启动拨号器活动。

          @Rule    
      public IntentsTestRule<DialerActivity> mActivityRule = new IntentsTestRule<>(
                  DialerActivity.class);
      
          private static final String PHONE_NUMBER = "1234567890";
          private static final Uri INTENT_DATA_PHONE_NUMBER = Uri.parse("tel:" + PHONE_NUMBER);
          private static String PACKAGE_ANDROID_DIALER = "com.android.phone";
      
          static {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                  // Starting with Android Lollipop the dialer package has changed. 
      
                  PACKAGE_ANDROID_DIALER = "com.android.server.telecom";
              }
          }
      
          @Test    public void testDialerIntent()throws Exception
          {
              intending(not(isInternal())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
              onView(withId(R.id.edit_text_caller_number)).perform(typeText(PHONE_NUMBER));
              onView(withId(R.id.button_call_number)).perform(click());
              intended(allOf(
                      hasAction(Intent.ACTION_CALL),
                      hasData(INTENT_DATA_PHONE_NUMBER),
                      toPackage(PACKAGE_ANDROID_DIALER)));
          }
      
      
      }
      

      更详细的描述请参考我的博文—— http://qaautomated.blogspot.in/2016/02/how-to-test-dialer-activity-with.html

      【讨论】:

      • 复制粘贴,没有任何解释正在做什么或与问题相关的上下文。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多