Jeśli implementujesz lokalny Service
jako komponent aplikacji, możesz utworzyć testy instruktażowe, aby sprawdzić, czy jego działanie jest prawidłowe.
AndroidX Test udostępnia interfejs API do testowania obiektów Service
w izolacji. Klasa ServiceTestRule
jest regułą JUnit 4, która uruchamia usługę przed uruchomieniem metod testowania jednostkowego i wyłącza usługę po zakończeniu testów. Więcej informacji o regułach JUnit 4 znajdziesz w dokumentacji JUnit.
Konfigurowanie środowiska testowego
Zanim utworzysz test integracji dla usługi, skonfiguruj swój projekt pod kątem testów z instrumentacją zgodnie z opisem w sekcji Konfigurowanie projektu na potrzeby testu AndroidX.
Tworzenie testu integracji dla usług
Test integracji powinien być napisany jako klasa testowa JUnit 4. Więcej informacji o tworzeniu klas testowych JUnit 4 i używaniu metod asercji JUnit 4 znajdziesz w artykule o tworzeniu instrumentowanych klasy testowej.
Utwórz w teście instancję ServiceTestRule
, korzystając z adnotacji @Rule
.
Kotlin
@get:Rule val serviceRule = ServiceTestRule()
Java
@Rule public final ServiceTestRule serviceRule = new ServiceTestRule();
Poniższy przykład pokazuje, jak możesz wdrożyć test integracji dla usługi. Metoda testowa testWithBoundService()
sprawdza, czy aplikacja łączy się z usługą lokalną i czy interfejs usługi działa prawidłowo.
Kotlin
@Test @Throws(TimeoutException::class) fun testWithBoundService() { // Create the service Intent. val serviceIntent = Intent( ApplicationProvider.getApplicationContext<Context>(), LocalService::class.java ).apply { // Data can be passed to the service via the Intent. putExtra(SEED_KEY, 42L) } // Bind the service and grab a reference to the binder. val binder: IBinder = serviceRule.bindService(serviceIntent) // Get the reference to the service, or you can call // public methods on the binder directly. val service: LocalService = (binder as LocalService.LocalBinder).getService() // Verify that the service is working correctly. assertThat(service.getRandomInt(), `is`(any(Int::class.java))) }
Java
@Test public void testWithBoundService() throws TimeoutException { // Create the service Intent. Intent serviceIntent = new Intent(ApplicationProvider.getApplicationContext(), 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 = serviceRule.bindService(serviceIntent); // Get the reference to the service, or you can call // public methods on the binder directly. LocalService service = ((LocalService.LocalBinder) binder).getService(); // Verify that the service is working correctly. assertThat(service.getRandomInt()).isAssignableTo(Integer.class); }
Dodatkowe materiały
Więcej informacji na ten temat znajdziesz w tych dodatkowych materiałach: