Android 单元测试之UI测试

发表于:2022-5-10 09:24

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:fb0122    来源:稀土掘金

分享:
  Espresso是Google官方的一个针对Android UI测试的库,可以自动化的进行UI测试。
  Espresso可以验证View的可见性,文字显示是否正确,图片是否正确,位置等等,相对于人工测试,Espresso覆盖更全,测试速度更快。
  UI测试分为三个部分:ViewMatcher、ViewAction、ViewAssertion。
  一般的测试流程就是按照上面图示的步骤来进行,首先匹配到UI组件,然后执行一些操作,比如click(),然后执行断言判断。其中每个部分包括很多个方法,官方有一个图:
  可以看到每个步骤下面有很多个方法,在写测试用例的时候都可以使用。
  普通UI组件测试
  对于普通的UI组件测试,在之前的Junit的测试中说,所有UI测试相关的都在androidTest文件夹下,看下一个简单的例子:
  @RunWith(AndroidJUnit4::class)
  class MainActivityTest {
  @get:Rule
  public val activity = ActivityTestRule(MainActivity::class.java)
  @Test
  fun onViewClicked() {
  onView(withId(R.id.tv_content)).check(matches(not(isDisplayed())))
  onView(withId(R.id.btn_change)).check(matches(withText("change"))).perform(click())
  onView(withId(R.id.tv_content)).check(matches(withText("content"))).check(matches(isDisplayed()))
  }
  }

  可以看出,测试UI的流程就是按照上面的三个步骤来进行的。
  Intent跳转测试
  引入:
  androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'

  复制代码在一些场景下,可能需要测试Intent的跳转,但是可能并不需要真正去执行这个跳转的操作,实际上只需要验证一下这个跳转的intent是否发送成功就可以了。Espresso提供了两个方法:intended 和 indending,这两个方法分别可以看成是Mockito中的verify()和when (),一般情况下,如果跳转不需要返回值,就使用 intended ,如果跳转需要返回值,则用 indending 模拟一个返回值。看一个简单的例子:
  //如果需要测试Intent,这里的Rule需要更换成IntentTestRule
  @get:Rule
  public val intentRule = IntentsTestRule(MainActivity::class.java)
  private val PACKAGE_NAME = "com.example.myapplication"
  @Test
  fun onIntent(){
      onView(withId(R.id.btn_intent)).perform(click())
  //点击btn跳转到SecondActivity, 验证intent中是否包含有SecondActivity组件,以及目标package是否为指定的package。
      intended(allOf(hasComponent(hasShortClassName(".SecondActivity")), toPackage(PACKAGE_NAME)))
  }

  如果使用的是startActivityforResult的话,需要返回值,可以按照如下的写法:
  val resultIntent = Intent()
  resultIntent.putExtra("result", "OK")
  val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultIntent)
  intending(allOf(hasComponent(hasShortClassName(".SecondActivity")), toPackage(PACKAGE_NAME))).respondWith(result)

  上面的代码就是利用intending对目标Intent构造了一个返回值,和 when().thenReturn() 有点类似。
  WebView 测试
  引入:
  androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0'
  除了对于一些普通的控件进行UI测试之外,Espresso还可以对WebView进行测试,并且可以获取web页中的element,对其进行一些Action、或者获取当前加载的url、也可以检查某些控件中是否包含有某些字段,下面是一个简单的例子:
  @Test
  fun onLoadUrl(){
  onView(withId(R.id.btn_start_webview)).perform(click())
  //onIdle()
  //检测当前加载的url中是否包含bing
  onWebView().check(webMatches(getCurrentUrl(), containsString("bing")))
  }

  还可以检测WebView中元素,并且进行断言判断:
  onWebView()
      .withElement(findElement(Locator.ID, "teacher"))
      .withContextualElement(findElement(Locator.ID, "person_name"))
      .check(webMatches(getText(), containsString("Socrates")))

  检测teacher.person_name是否包含有Socrates。
  也可以对WebView中的元素进行操作:
  onWebView()
      .withElement(findElement(Locator.ID, "teacher"))
      .perform(webClick())

  自定义Matcher
  在一些情况下,可能系统提供的Matcher并不能满足需求,这时候也可以通过自定义Matcher来实现:
  fun textViewTextColorMatcher(matcherColor: Int): Matcher<View> {
      return object: BoundedMatcher<View, TextView>(TextView::class.java){
          override fun describeTo(description: Description?) {
              description?.appendText("with test color: $matcherColor")
          }
          override fun matchesSafely(item: TextView?): Boolean {
              return matcherColor == item?.currentTextColor
          }
      }
  }

  上述代码自定义了一个TextView的textColor的匹配器,describeTo是当匹配失败的时候的提示,matchesSafely是主要的匹配逻辑。
  然后就可以通过以下方式来使用自定义的匹配器了。
  onView(withId(R.id.search_action_button)).check(matches(textViewTextColorMatcher(TEXT_BTN_COLOR_DISABLED)))

  其它
  · 测试报告
  当使用gralde/app/verification/test 编译的时候,会运行所有的测试类(包括所有的module),并且在对应的build/reports/tests/下面生成一个测试报告(也可以通过运行命令 ./gradlew test)。可以通过这个测试报告来查看到底有多少测试类通过,多少失败,然后针对性的检查问题。下图就是跑了test之后生成的报告:
  · 使用Jacoco生成单元测试覆盖率报告
  下图是集成到了demo里的jacoco输出的覆盖率报告:
  可以看到有覆盖率的分析,包括代码覆盖率、分支覆盖率等等。

  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号