Android: юнит-тестирование сервиса

В настоящее время я пытаюсь написать приложение для Android с использованием TDD. Мне дали задание написать сервис, который будет очень важен для приложения.

По этой причине я пытаюсь написать надлежащий тест для сервиса. В руководствах по Android указано следующее:

В разделе «Что тестировать» приведены общие рекомендации по тестированию компонентов Android. Вот некоторые конкретные рекомендации по тестированию Сервиса:

  • Убедитесь, что onCreate () вызывается в ответ на Context.startService () или Context.bindService (). Точно так же вы должны убедиться, что onDestroy () вызывается в ответ на Context.stopService (), Context.unbindService (), stopSelf () или stopSelfResult (). Убедитесь, что ваша служба правильно обрабатывает несколько вызовов из Context.startService (). Только первый вызов вызывает Service.onCreate (), но все вызовы инициируют вызов Service.onStartCommand ().

  • Кроме того, помните, что вызовы startService () не являются вложенными, поэтому один вызов Context.stopService () или Service.stopSelf () (но не stopSelf (int)) остановит Сервис. Вы должны проверить, что ваша служба останавливается в правильной точке.

  • Протестируйте любую бизнес-логику, которую реализует ваша служба. Бизнес-логика включает проверку на недопустимые значения, финансовые и арифметические вычисления и т. Д.

Источник: Сервисное тестирование | Разработчики Android

Я еще не видел надлежащего теста для этих методов жизненного цикла, множественных вызовов Context.startService () и т. Д. Я пытаюсь выяснить это, но я ' м в настоящее время в растерянности.

Я пытаюсь протестировать службу с помощью класса ServiceTestCase:

import java.util.List;

import CoreManagerService;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.test.ServiceTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;

/**
 * 
 * This test should be executed on an actual device as recommended in the testing fundamentals.
 * http://developer.android.com/tools/testing/testing_android.html#WhatToTest
 * 
 * The following page describes tests that should be written for a service.
 * http://developer.android.com/tools/testing/service_testing.html
 * TODO: Write tests that check the proper execution of the service's life cycle.
 * 
 */
public class CoreManagerTest extends ServiceTestCase {

    /** Tag for logging */
    private final static String TAG = CoreManagerTest.class.getName();

    public CoreManagerTest () {
        super(CoreManagerService.class);
    }

    public CoreManagerTest(Class serviceClass) {
        super(serviceClass);

        // If not provided, then the ServiceTestCase will create it's own mock
        // Context.
        // setContext();
        // The same goes for Application.
        // setApplication();

        Log.d(TAG, "Start of the Service test.");
    }

    @SmallTest
    public void testPreConditions() {
    }

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
        super.setUp();
    }

    @After
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testStartingService() {
        getSystemContext().startService(new Intent(getSystemContext(), CoreManagerService.class));

        isServiceRunning();
    }

    private void isServiceRunning() {
        final ActivityManager activityManager = (ActivityManager)this.getSystemContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        final List services = activityManager
                .getRunningServices(Integer.MAX_VALUE);

        boolean serviceFound = false;
        for (RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(
                    CoreManagerService.class.toString())) {
                serviceFound = true;
            }
        }
        assertTrue(serviceFound);
    }
}

Я неправильно подхожу к этому? Должен ли я использовать тест активности, чтобы проверить привязку службы к?

11
задан Julian Suarez 10 April 2017 в 17:03
поделиться