我如何单元测试一个Android活动的加速度计,其作用?加速度计、单元测试、作用、Android

2023-09-06 10:59:06 作者:一见你就硬

我开始基于关闭此 ShakeActivity 的一个活动,我想写一些单元测试它。我已经写了一些小的单元测试之前,Android的活动,但我不知道从哪里开始在这里。我想喂加速一些不同的价值观和怎么考活动响应了。现在我保持简单,只更新私人诠释计数器变量和一个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);
}