# ServiceTestRule

Artifact: [androidx.test:rules](https://developer.android.com/jetpack/androidx/releases/test) [View Source](https://cs.android.com/search?q=file:androidx/test/rule/ServiceTestRule.java+class:androidx.test.rule.ServiceTestRule)

*** ** * ** ***


```
public class ServiceTestRule implements TestRule
```

<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.sourceforge.net/javadoc/org/junit/After.html) are finished.

Note: This rule doesn't support `https://developer.android.com/reference/android/app/IntentService.html` because it's automatically destroyed when `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());
}
```

## Summary

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

| ### Protected constructors |
|---|
| `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#ServiceTestRule(long,java.util.concurrent.TimeUnit)(long timeout, https://developer.android.com/reference/java/util/concurrent/TimeUnit.html timeUnit)` |

| ### Public methods |
|---|---|
| `https://junit.org/junit4/javadoc/latest/org/junit/runners/model/Statement.html` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#apply(org.junit.runners.model.Statement,org.junit.runner.Description)(https://junit.org/junit4/javadoc/latest/org/junit/runners/model/Statement.html base, https://junit.org/junit4/javadoc/latest/org/junit/runner/Description.html description)` |
| `https://developer.android.com/reference/android/os/IBinder.html` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent)(@https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/android/content/Intent.html intent)` Works just like `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent,android.content.ServiceConnection,int)` except uses an internal `https://developer.android.com/reference/android/content/ServiceConnection.html` to guarantee successful bound. |
| `https://developer.android.com/reference/android/os/IBinder.html` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent,android.content.ServiceConnection,int)( @https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/android/content/Intent.html intent, @https://developer.android.com/reference/androidx/annotation/NonNull 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 `https://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)` with an `https://developer.android.com/reference/android/content/Intent.html` that identifies a service. |
| `void` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#startService(android.content.Intent)(@https://developer.android.com/reference/androidx/annotation/NonNull 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 `https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)` with an `https://developer.android.com/reference/android/content/Intent.html` that identifies a service. |
| `void` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#unbindService()()` Unbinds the service under test that was previously bound by a call to `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent)` or `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent,android.content.ServiceConnection,int)`. |
| `static https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` | `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#withTimeout(long,java.util.concurrent.TimeUnit)(long timeout, https://developer.android.com/reference/java/util/concurrent/TimeUnit.html timeUnit)` Factory method to create a `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` with a custom timeout |

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

## Public constructors

### ServiceTestRule

```
public ServiceTestRule()
```

Creates a `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` with a default timeout of 5 seconds

## Protected constructors

### ServiceTestRule

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

## Public methods

### apply

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

### bindService

```
public IBinder bindService(@NonNull Intent intent)
```

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

| Throws |
|---|---|
| `https://developer.android.com/reference/java/util/concurrent/TimeoutException.html` |   |

| See also |
|---|---|
| `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent,android.content.ServiceConnection,int)` |   |

### bindService

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

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

| Parameters |
|---|---|
| `@https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/android/content/Intent.html 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 `https://developer.android.com/reference/android/content/IntentFilter.html` published by a service. |
| `@https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/android/content/ServiceConnection.html connection` | Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null. |
| `int flags` | Operation options for the binding. May be 0, `https://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE`, `https://developer.android.com/reference/android/content/Context.html#BIND_DEBUG_UNBIND`, `https://developer.android.com/reference/android/content/Context.html#BIND_NOT_FOREGROUND`, `https://developer.android.com/reference/android/content/Context.html#BIND_ABOVE_CLIENT`, `https://developer.android.com/reference/android/content/Context.html#BIND_ALLOW_OOM_MANAGEMENT`, or `https://developer.android.com/reference/android/content/Context.html#BIND_WAIVE_PRIORITY`. |

| Returns |
|---|---|
| `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. |

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

| See also |
|---|---|
| `https://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE` |   |
| `https://developer.android.com/reference/android/content/Context.html#BIND_DEBUG_UNBIND` |   |
| `https://developer.android.com/reference/android/content/Context.html#BIND_NOT_FOREGROUND` |   |

### startService

```
public void startService(@NonNull Intent intent)
```

Starts the service under test and blocks until the service is connected, in the same way as if it were started by `https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)` with an `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 `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 `https://developer.android.com/reference/android/app/Service.html#onBind(android.content.Intent)` method returns `null` then a `https://developer.android.com/reference/java/util/concurrent/TimeoutException.html` will be thrown.

| Parameters |
|---|---|
| `@https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/android/content/Intent.html intent` | An Intent that identifies a service, of the same form as the Intent passed to `https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)`. |

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

### unbindService

```
public void unbindService()
```

Unbinds the service under test that was previously bound by a call to `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule#bindService(android.content.Intent)` or `https://developer.android.com/reference/androidx/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.

### withTimeout

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

Factory method to create a `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` with a custom timeout

| Parameters |
|---|---|
| `long timeout` | the amount of time to wait for a service to connect. |
| `https://developer.android.com/reference/java/util/concurrent/TimeUnit.html timeUnit` | the time unit representing how the timeout parameter should be interpreted |

| Returns |
|---|---|
| `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` | a `https://developer.android.com/reference/androidx/test/rule/ServiceTestRule` with the desired timeout |

## Protected methods

### afterService

```
protected 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.sourceforge.net/javadoc/org/junit/After.html) and after necessary calls to stop (or unbind) the service under test were called.

### beforeService

```
protected 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.sourceforge.net/javadoc/org/junit/Before.html). Do not start or bind to a service from here!