《Android编程权威指南》之音频播放与单元测试(二)

《Android编程权威指南》第 20 章第二篇,补充完 BeatBox 应用的单元测试啦。

八、编写测试函数

测试函数将用到 @Test 注解。

 @Test
    fun exposesSoundNameAsTitle(){
        assertThat(subject.title,`is`(sound.name))
    } 

assertThat(…) 选 org.junit 库里的 Assert.assertThat(…) 函数,is(…) 选 org.hamcrest 库里的 Is.is 函数。

上面代码意思是断定测试对象获取标题函数和 sound 的获取文件名函数返回相同的值。如果不同,单元测试失败。

接下来测试 SoundViewModel 和 BeatBox.play(Sound) 的交互。

 @Test
    fun callsBeatBoxPlayOnButtonClicked(){
        subject.onButtonClicked()
    } 

为了测试 SoundViewModel 不让它跟 BeatBox 绑太死,不依赖 BeatBox 对象,就在此测试案例中模拟出 BeatBox 对象。

class SoundViewModelTest {
    ...
    private lateinit var beatBox: BeatBox
    @Before
    fun setUp() {
        beatBox = mock(BeatBox::class.java)
        ...
    }
    ...
} 

Mockito 的 verify(Object) 可以确认,要测试的函数是否都按预期被调用了。

 @Test
    fun callsBeatBoxPlayOnButtonClicked(){
        ...
        verify(beatBox).play(sound)
    } 

失败了

然后按照书中过程补充修正一下,把 BeatBox 传给 SoundViewModel,修正 SoundHolder 中的错误,在测试类里提供模拟板 BeatBox,实现 onButtonClicked() 函数。具体代码略了,见 Demo。

通过了

九、数据绑定回调

在布局文件里,添加数据绑定 lambda 表达式,让按钮对象和 SoundViewModel.onButtonClicked() 函数关联起来。

 <Button
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:onClick="@
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值