如何对作用于加速度计的 Android Activity 进行单元测试? [英] How can I unit test an Android Activity that acts on Accelerometer?
问题描述
我从一个基于这个 ShakeActivity 的活动开始,我想写一些对其进行单元测试.我之前为 Android 活动编写了一些小型单元测试,但我不确定从哪里开始.我想为加速度计提供一些不同的值并测试活动如何响应它.现在我保持简单,只是在摇动"事件发生时更新一个私有的 int 计数器变量和一个 TextView.
I am starting with an Activity based off of this ShakeActivity and I want to write some unit tests for it. I have written some small unit tests for Android activities before but I'm not sure where to start here. I want to feed the accelerometer some different values and test how the activity responds to it. For now I'm keeping it simple and just updating a private int counter variable and a TextView when a "shake" event happens.
所以我的问题主要归结为:
So my question largely boils down to this:
如何将单元测试中的虚假数据发送到加速度计?
推荐答案
我的解决方案最终比我预期的要简单得多.我并没有真正测试加速度计,而是测试应用程序对加速度计引发的事件的响应,我只需要进行相应的测试.我的班级实现了 SensorListener,我想测试 onSensorChanged 会发生什么.关键是输入一些值并检查我的活动状态.示例:
My solution to this ended up way simpler then I expected. I'm not really testing the accelerometer so much as I am testing the application's response to an event raised by the accelerometer, and I just needed to test accordingly. My class implements SensorListener and I wanted to test what happens onSensorChanged. The key then was to feed in some values and check my Activity's state. Example:
public void testShake() throws InterruptedException {
mShaker.onSensorChanged(SensorManager.SENSOR_ACCELEROMETER, new float[] {0, 0, 0} );
//Required because method only allows one shake per 100ms
Thread.sleep(500);
mShaker.onSensorChanged(SensorManager.SENSOR_ACCELEROMETER, new float[] {300, 300, 300});
Assert.assertTrue("Counter: " + mShaker.shakeCounter, mShaker.shakeCounter > 0);
}
这篇关于如何对作用于加速度计的 Android Activity 进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!