# ServiceTestRule

Summary:[Ctors](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#pubctors)\|[Methods](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#pubmethods)\|[Protected Methods](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#promethods)\|[Inherited Methods](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#inhmethods)\|[\[Expand All\]](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#)  

# ServiceTestRule

| This package is part of the Android[support library](https://developer.android.com/topic/libraries/support-library)which is no longer maintained. The support library has been superseded by[AndroidX](https://developer.android.com/jetpack/androidx)which is part of[Jetpack](https://developer.android.com/jetpack). We recommend using the AndroidX libraries in all new projects. You should also consider[migrating](https://developer.android.com/jetpack/androidx/migrate)existing projects to AndroidX. To find the AndroidX class that maps to this deprecated class, see the AndroidX support library[class mappings](https://developer.android.com/jetpack/androidx/migrate/class-mappings).

`
public


class
ServiceTestRule
`  
`

extends `[Object](https://developer.android.com/reference/java/lang/Object.html)`


``


implements

TestRule


`

|---|-------------------------------------------|
| [java.lang.Object](https://developer.android.com/reference/java/lang/Object.html) ||
| ↳ | android.support.test.rule.ServiceTestRule |

<br />

*** ** * ** ***

A JUnit rule that provides a simplified mechanism to start and shutdown your service before and after the duration of your test. It also guarantees that the service is successfully connected when starting (or binding to) a service. The service can be started (or bound) using one of the helper methods. It will automatically be stopped (or unbound) after the test completes and any methods annotated with[`
After`](http://junit.source.net/javadoc/org/junit/After.html)are finished.

Note: This rule doesn't support[IntentService](https://developer.android.com/reference/android/app/IntentService.html)because it's automatically destroyed when[onHandleIntent(android.content.Intent)](https://developer.android.com/reference/android/app/IntentService.html#onHandleIntent(android.content.Intent))finishes all outstanding commands. So there is no guarantee to establish a successful connection in a timely manner.

Usage:  

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

 @Test
 public void testWithStartedService() {
     mServiceRule.startService(
         new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
     //do something
 }

 @Test
 public void testWithBoundService() {
     IBinder binder = mServiceRule.bindService(
         new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
     MyService service = ((MyService.LocalBinder) binder).getService();
     assertTrue("True wasn't returned", service.doSomethingToReturnTrue());
 }
 
```

<br />

**This API is currently in beta.**

## Summary

|                                                                                                                              ### Public constructors                                                                                                                               ||
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---|
| ` `[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#ServiceTestRule())`() ` Creates a[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)with a default timeout of 5 seconds |

|                                                                                                                                                                                                                                                                                                                                                                                                                                                  ### Public methods                                                                                                                                                                                                                                                                                                                                                                                                                                                   ||
|----------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ` Statement`                                                                                                   | ` `[apply](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#apply(org.junit.runners.model.Statement, org.junit.runner.Description))`(Statement base, Description description) `                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ` `[IBinder](https://developer.android.com/reference/android/os/IBinder.html)                                  | ` `[bindService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent))`(`[Intent](https://developer.android.com/reference/android/content/Intent.html)` intent) ` Works just like[bindService(android.content.Intent, android.content.ServiceConnection, int)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int))except uses an internal[ServiceConnection](https://developer.android.com/reference/android/content/ServiceConnection.html)to guarantee successful bound.                                                                                                                                                |
| ` `[IBinder](https://developer.android.com/reference/android/os/IBinder.html)                                  | ` `[bindService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int))`(`[Intent](https://developer.android.com/reference/android/content/Intent.html)` intent, `[ServiceConnection](https://developer.android.com/reference/android/content/ServiceConnection.html)` connection, int flags) ` Binds the service under test, in the same way as if it were started by[Context.bindService(Intent, ServiceConnection, flags)](https://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int))with an[Intent](https://developer.android.com/reference/android/content/Intent.html)that identifies a service. |
| ` void`                                                                                                        | ` `[startService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#startService(android.content.Intent))`(`[Intent](https://developer.android.com/reference/android/content/Intent.html)` intent) ` Starts the service under test and blocks until the service is connected, in the same way as if it were started by[Context.startService(Intent)](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent))with an[Intent](https://developer.android.com/reference/android/content/Intent.html)that identifies a service.                                                                                                                                                                                         |
| ` void`                                                                                                        | ` `[unbindService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#unbindService())`() ` Unbinds the service under test that was previously bound by a call to[bindService(android.content.Intent)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent))or[bindService(android.content.Intent, android.content.ServiceConnection, int)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int)).                                                                                                                                                                                           |
| ` static `[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule) | ` `[withTimeout](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#withTimeout(long, java.util.concurrent.TimeUnit))`(long timeout, `[TimeUnit](https://developer.android.com/reference/java/util/concurrent/TimeUnit.html)` timeUnit) ` Factory method to create a[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)with a custom timeout                                                                                                                                                                                                                                                                                                                                                                          |

|                                                                                                               ### Protected methods                                                                                                                ||
|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ` void` | ` `[afterService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#afterService())`() ` Override this method to do your own service specific clean up after the service is shutdown.                     |
| ` void` | ` `[beforeService](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#beforeService())`() ` Override this method to do your own service specific initialization before starting or binding to the service. |

| ### Inherited methods |
|-----------------------|---|
| [![](https://developer.android.com/static/assets/images/styles/disclosure_down.png)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#)From class` `[java.lang.Object](https://developer.android.com/reference/java/lang/Object.html)` ` |-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------| | ` `[Object](https://developer.android.com/reference/java/lang/Object.html)          | ` clone() `                                                                                | | ` boolean`                                                                          | ` equals(`[Object](https://developer.android.com/reference/java/lang/Object.html)` arg0) ` | | ` void`                                                                             | ` finalize() `                                                                             | | ` final `[Class](https://developer.android.com/reference/java/lang/Class.html)`<?>` | ` getClass() `                                                                             | | ` int`                                                                              | ` hashCode() `                                                                             | | ` final void`                                                                       | ` notify() `                                                                               | | ` final void`                                                                       | ` notifyAll() `                                                                            | | ` `[String](https://developer.android.com/reference/java/lang/String.html)          | ` toString() `                                                                             | | ` final void`                                                                       | ` wait(long arg0, int arg1) `                                                              | | ` final void`                                                                       | ` wait(long arg0) `                                                                        | | ` final void`                                                                       | ` wait() `                                                                                 | ||
| [![](https://developer.android.com/static/assets/images/styles/disclosure_down.png)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#)From interface` org.junit.rules.TestRule ` |-----------------------|---------------------------------------------| | ` abstract Statement` | ` apply(Statement arg0, Description arg1) ` | ||

## Public constructors

### ServiceTestRule

```
ServiceTestRule ()
```

Creates a[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)with a default timeout of 5 seconds

<br />

## Public methods

### apply

```
Statement apply (Statement base, 
                Description description)
```

<br />

<br />

|             Parameters              ||
|---------------|----------------------|
| `base`        | `Statement` <br />   |
| `description` | `Description` <br /> |

|       Returns       ||
|-------------|--------|
| `Statement` | <br /> |

### bindService

```
IBinder bindService (Intent intent)
```

Works just like[bindService(android.content.Intent, android.content.ServiceConnection, int)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int))except uses an internal[ServiceConnection](https://developer.android.com/reference/android/content/ServiceConnection.html)to guarantee successful bound. The operation option flag defaults to[BIND_AUTO_CREATE](https://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE)

<br />

|        Parameters         ||
|----------|-----------------|
| `intent` | `Intent` <br /> |

|                                      Returns                                       ||
|----------------------------------------------------------------------------|--------|
| [IBinder](https://developer.android.com/reference/android/os/IBinder.html) | <br /> |

|                                                  Throws                                                   ||
|--------------------------------------------------------------------------------------------------------|---|
| [TimeoutException](https://developer.android.com/reference/java/util/concurrent/TimeoutException.html) |   |

**See also:**

- [bindService(android.content.Intent, android.content.ServiceConnection, int)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int))  

### bindService

```
IBinder bindService (Intent intent, 
                ServiceConnection connection, 
                int flags)
```

Binds the service under test, in the same way as if it were started by[Context.bindService(Intent,
ServiceConnection, flags)](https://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int))with an[Intent](https://developer.android.com/reference/android/content/Intent.html)that identifies a service. However, it waits for[onServiceConnected(android.content.ComponentName, android.os.IBinder)](https://developer.android.com/reference/android/content/ServiceConnection.html#onServiceConnected(android.content.ComponentName, android.os.IBinder))to be called before returning.

<br />

|                                                                                                                                                                                                                                                                                                                                                                                Parameters                                                                                                                                                                                                                                                                                                                                                                                 ||
|--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `intent`     | `Intent`: Identifies the service to connect to. The Intent may specify either an explicit component name, or a logical description (action, category, etc) to match an[IntentFilter](https://developer.android.com/reference/android/content/IntentFilter.html)published by a service. <br />                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `connection` | `ServiceConnection`: Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null. <br />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `flags`      | `int`: Operation options for the binding. May be 0,[BIND_AUTO_CREATE](https://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE),[BIND_DEBUG_UNBIND](https://developer.android.com/reference/android/content/Context.html#BIND_DEBUG_UNBIND),[BIND_NOT_FOREGROUND](https://developer.android.com/reference/android/content/Context.html#BIND_NOT_FOREGROUND),[BIND_ABOVE_CLIENT](https://developer.android.com/reference/android/content/Context.html#BIND_ABOVE_CLIENT),[BIND_ALLOW_OOM_MANAGEMENT](https://developer.android.com/reference/android/content/Context.html#BIND_ALLOW_OOM_MANAGEMENT), or[BIND_WAIVE_PRIORITY](https://developer.android.com/reference/android/content/Context.html#BIND_WAIVE_PRIORITY). <br /> |

|                                                                                   Returns                                                                                    ||
|----------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|
| [IBinder](https://developer.android.com/reference/android/os/IBinder.html) | An object whose type is a subclass of IBinder, for making further calls into the service. <br /> |

|                                                                                   Throws                                                                                    ||
|--------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------|
| [SecurityException](https://developer.android.com/reference/java/lang/SecurityException.html)          | if the called doesn't have permission to bind to the given service. |
| [TimeoutException](https://developer.android.com/reference/java/util/concurrent/TimeoutException.html) | if timed out waiting for a successful connection with the service.  |

**See also:**

- [BIND_AUTO_CREATE](https://developer.android.com/https://developer.android.com/reference/android/content/Context#BIND_AUTO_CREATE)
- [BIND_DEBUG_UNBIND](https://developer.android.com/https://developer.android.com/reference/android/content/Context#BIND_DEBUG_UNBIND)
- [BIND_NOT_FOREGROUND](https://developer.android.com/https://developer.android.com/reference/android/content/Context#BIND_NOT_FOREGROUND)  

### startService

```
void startService (Intent intent)
```

Starts the service under test and blocks until the service is connected, in the same way as if it were started by[Context.startService(Intent)](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent))with an[Intent](https://developer.android.com/reference/android/content/Intent.html)that identifies a service. If you use this method to start the service, it is automatically stopped at the end of the test run. However, it also attempts to bind to the service and waits for[onServiceConnected(android.content.ComponentName, android.os.IBinder)](https://developer.android.com/reference/android/content/ServiceConnection.html#onServiceConnected(android.content.ComponentName, android.os.IBinder))to be called to ensure successful connection.

**Note:** This method only supports services that allow clients to bind to them. In other words, if your service[onBind(Intent)](https://developer.android.com/reference/android/app/Service.html#onBind(android.content.Intent))method returns`null`then a[TimeoutException](https://developer.android.com/reference/java/util/concurrent/TimeoutException.html)will be thrown.

<br />

|                                                                                                                     Parameters                                                                                                                      ||
|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `intent` | `Intent`: An Intent that identifies a service, of the same form as the Intent passed to[Context.startService (Intent)](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)). <br /> |

|                                                                                   Throws                                                                                   ||
|--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
| [SecurityException](https://developer.android.com/reference/java/lang/SecurityException.html)          | if you do not have permission to bind to the given service.        |
| [TimeoutException](https://developer.android.com/reference/java/util/concurrent/TimeoutException.html) | if timed out waiting for a successful connection with the service. |

### unbindService

```
void unbindService ()
```

Unbinds the service under test that was previously bound by a call to[bindService(android.content.Intent)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent))or[bindService(android.content.Intent, android.content.ServiceConnection, int)](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule#bindService(android.content.Intent, android.content.ServiceConnection, int)). You normally do not need to call this method since your service will automatically be stopped and unbound at the end of each test method.

<br />

### withTimeout

```
ServiceTestRule withTimeout (long timeout, 
                TimeUnit timeUnit)
```

Factory method to create a[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)with a custom timeout

<br />

|                                                Parameters                                                 ||
|------------|-----------------------------------------------------------------------------------------------|
| `timeout`  | `long`: the amount of time to wait for a service to connect. <br />                           |
| `timeUnit` | `TimeUnit`: the time unit representing how the timeout parameter should be interpreted <br /> |

|                                                                                                                  Returns                                                                                                                   ||
|------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
| [ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule) | a[ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)with the desired timeout <br /> |

## Protected methods

### afterService

```
void afterService ()
```

Override this method to do your own service specific clean up after the service is shutdown. The method is called after each test method is executed including any method annotated with[`After`](http://junit.source.net/javadoc/org/junit/After.html)and after necessary calls to stop (or unbind) the service under test were called.

<br />

### beforeService

```
void beforeService ()
```

Override this method to do your own service specific initialization before starting or binding to the service. The method is called before each test method is executed including any method annotated with[`
Before`](http://junit.source.net/javadoc/org/junit/Before.html). Do not start or bind to a service from here!

<br />

-

  ## Classes

  - [ActivityTestRule](https://developer.android.com/reference/android/support/test/rule/ActivityTestRule)
  - [DisableOnAndroidDebug](https://developer.android.com/reference/android/support/test/rule/DisableOnAndroidDebug)
  - [GrantPermissionRule](https://developer.android.com/reference/android/support/test/rule/GrantPermissionRule)
  - [ServiceTestRule](https://developer.android.com/reference/android/support/test/rule/ServiceTestRule)
  - [UiThreadTestRule](https://developer.android.com/reference/android/support/test/rule/UiThreadTestRule)