Android: get a link to the service you started in the test

I am trying to write a test test for my NetworkMonitorService , as described in the official documentation testing your service .

I am currently stuck because I can’t understand how I can get a link to a service I started to insert layouts into it and approve the behavior.

My code is:

 @RunWith(AndroidJUnit4.class) @SmallTest public class NetworkMonitorServiceTest { @Rule public final ServiceTestRule mServiceTestRule = new ServiceTestRule(); @Test public void serviceStarted_someEventHappenedInOnStartCommand() { try { mServiceTestRule.startService(new Intent( InstrumentationRegistry.getTargetContext(), NetworkMonitorService.class)); } catch (TimeoutException e) { throw new RuntimeException("timed out"); } // I need a reference to the started service in order to assert that some event happened // in onStartCommand()... } } 

The service in question does not support binding. I think that if I implemented binding support and then used this in a test to get a link to a service, it could work. However, I don't like writing production code just to support test cases ...

So, how can I test (test) a Service that does not support binding?

+2
source share
1 answer

Replace the application with the special version "for tests". Do this by providing a custom test test. Mock your dependencies, this is a "test application." See details

Here is a simplified example of how you can use the app for testing. Suppose you want to break the network layer (e.g. Api ) during tests.

 public class App extends Application { public Api getApi() { return realApi; } } public class MySerice extends Service { private Api api; @Override public void onCreate() { super.onCreate(); api = ((App) getApplication()).getApi(); } } public class TestApp extends App { private Api mockApi; @Override public Api getApi() { return mockApi; } public void setMockApi(Api api) { mockApi = api; } } public class MyTest { @Rule public final ServiceTestRule mServiceTestRule = new ServiceTestRule(); @Before public setUp() { myMockApi = ... // init mock Api ((TestApp)InstrumentationRegistry.getTargetContext()).setMockApi(myMockApi); } @Test public test() { //start service //use mockApi for assertions } } 

In the example, dependency injection is performed using the getApi application getApi . But you can use the dagger or any other approaches in the same way.

+1
source

Source: https://habr.com/ru/post/1262359/


All Articles