应用程序的组件的集成测试

如果App使用了用户无法直接与之交互的组件,例如Service或Content Provider,那么你应该验证App中这些组件的行为的正确性。这时候就需要使用到Android的集成测试(integration test)。

集成测试,可以看作是对仪器级单元测试的重度使用,主要用来测试Android的非UI组件和自己编写的非UI组件,所以集成测试的编写规则要遵循仪器级单元测试的规则。

在集成测试中,每种Android的非UI组件都有自己对应的测试规则,下面就简单介绍Service。其它Android组件,请自行查找资料。

测试Service

public class LocalService extends Service {
    private static final String TAG = LocalService.class.getSimpleName();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        super.onDestroy();
    }
}

LocalService的Service实现

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    private static final String TAG = ExampleInstrumentedTest.class.getSimpleName();

    //@Rule
    //public final ServiceTestRule mServiceRule = new ServiceTestRule();

    @Test
    public void testServiceDemo() throws Exception {
        Log.d(TAG, "testServiceDemo: start");

        Context appContext = InstrumentationRegistry.getTargetContext();
        Intent intent = new Intent(appContext, LocalService.class);
        appContext.startService(intent);
        TimeUnit.MILLISECONDS.sleep(3000);
        appContext.stopService(intent);

        // Create the service Intent.
        //Intent serviceIntent = new Intent(appContext, LocalService.class);
        // Data can be passed to the service via the Intent.
        //serviceIntent.putExtra(LocalService.SEED_KEY, 42L);
        // Bind the service and grab a reference to the binder.
        //IBinder binder = mServiceRule.bindService(serviceIntent);
        // Get the reference to the service, or you can call
        // public methods on the binder directly.
        //LocalService service = ((LocalService.LocalBinder) binder).getService();

        Log.d(TAG, "testServiceDemo: over");
    }
}

Service的集成测试的示例代码

Service的集成测试的示例的Log信息
Service的集成测试的示例的Log信息

该示例演示了利用App的Context来启动和停止一个本地Service。

如果要使用boundService的话,那么可以利用ServiceTestRule类(该类的对象必须要用“@Rule”进行注解)来实现,这部分的示例代码的注释只实现了如何使用ServiceTestRule来实现绑定、获取Service的实现。

猜你喜欢

转载自blog.csdn.net/yumeizui8923/article/details/79448757