junit4 测试android,AndroidX Test 的 JUnit4 规则

AndroidX Test 包含需要与 AndroidJUnitRunner 一起使用的一组 JUnit 规则。JUnit 规则可提供更高的灵活性,并减少测试中所需的样板代码。

ActivityTestRule

此规则提供单个 Activity 的功能测试。被测 Activity 会在带有 @Test 注释的每个测试运行之前以及带有 @Before 注释的所有方法运行之前启动。它会在测试完成并且带有 @After 注释的所有方法结束后终止。如需在测试逻辑中访问被测的 Activity,请调用 ActivityTestRule.getActivity()。

注意:AndroidX Test 还包含一个 API ActivityScenario,它目前处于 Beta 版阶段。此 API 可在各种测试环境中运行,并在使用它的测试中提供线程安全。

我们建议您试用此 API,看看它如何帮助您推动应用 Activity 的生命周期。

以下代码段演示了如何将 ActivityTestRule 融入测试逻辑:

Kotlin

@RunWith(AndroidJUnit4::class.java)

@LargeTest

class MyClassTest {

@get:Rule

val activityRule = ActivityTestRule(MyClass::class.java)

@Test fun myClassMethod_ReturnsTrue() { ... }

}Java

@RunWith(AndroidJUnit4.class)

@LargeTest

public class MyClassTest {

@Rule

public ActivityTestRule activityRule =

new ActivityTestRule(MyClass.class);

@Test

public void myClassMethod_ReturnsTrue() { ... }

}

ServiceTestRule

此规则提供了一种简化的机制,用于在测试之前启动服务以及在测试之后关闭服务。它还可以保证在启动服务或绑定到服务时成功连接该服务。您可以使用某个辅助程序方法启动或绑定服务。它会在测试完成并且带有 @After 注释的所有方法结束后自动停止或取消绑定。

注意:此规则不支持 IntentService。这是因为,服务会在 IntentService.onHandleIntent(Intent) 完成所有未完成的命令后被销毁,因此无法保证及时建立成功的连接。

Kotlin

@RunWith(AndroidJUnit4::class.java)

@MediumTest

class MyServiceTest {

@get:Rule

val serviceRule = ServiceTestRule()

@Test fun testWithStartedService() {

serviceRule.startService(

Intent(ApplicationProvider.getApplicationContext(),

MyService::class.java))

// Add your test code here.

}

@Test fun testWithBoundService() {

val binder = serviceRule.bindService(

Intent(ApplicationProvider.getApplicationContext(),

MyService::class.java))

val service = (binder as MyService.LocalBinder).service

assertThat(service.doSomethingToReturnTrue()).isTrue()

}

}Java

@RunWith(AndroidJUnit4.class)

@MediumTest

public class MyServiceTest {

@Rule

public final ServiceTestRule serviceRule = new ServiceTestRule();

@Test

public void testWithStartedService() {

serviceRule.startService(

new Intent(ApplicationProvider.getApplicationContext(),

MyService.class));

// Add your test code here.

}

@Test

public void testWithBoundService() {

IBinder binder = serviceRule.bindService(

new Intent(ApplicationProvider.getApplicationContext(),

MyService.class));

MyService service = ((MyService.LocalBinder) binder).getService();

assertThat(service.doSomethingToReturnTrue()).isTrue();

}

}

其他资源

如需详细了解如何在 Android 测试中使用 JUnit 规则,请参阅以下资源。

示例

BasicSample:ActivityTestRule 的简单用法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值