I'm having issues creating unit tests for a Service in Android Studio. I have set up my project to perform unit tests and have successfully set up tests for a different (non-Service) class. I can run those tests and have them pass.
This is the code for my ServiceTestCase:
package com.roche.parkinsons.service;
import android.content.Intent;
import android.test.ServiceTestCase;
import android.util.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class GeneralServiceTest extends ServiceTestCase<GeneralService> {
/** Tag for logging */
private final static String TAG = GeneralServiceTest.class.getName();
public GeneralServiceTest() {
super(GeneralService.class);
}
//
@Before
public void setUp() throws Exception {
super.setUp();
Log.d(TAG, "Setup complete");
}
@After
public void tearDown() throws Exception {
Log.d(TAG, "Teardown complete");
super.tearDown();
}
@Test
public void testOnCreate() throws Exception {
Intent intent = new Intent(getSystemContext(), GeneralService.class);
startService(intent);
assertNotNull(getService());
}
}
As you can see it is about as simple as I can make it. It does not matter what I try, assertNotNull always fails.
From debugging the test, I have found that the intent created with:
Intent intent = new Intent(getSystemContext(), GeneralService.class);
always returns null.
I have tried setting the context and class like so
public void testOnCreate() throws Exception {
Intent intent = new Intent(getSystemContext(), GeneralService.class);
intent.setClass(getSystemContext(), GeneralService.class);
startService(intent);
assertNotNull(getService());
}
But this has no effect.
I'm out of ideas. There are very few examples for ServiceTestCase that aren't years out of date and of those I have found (such as here: http://alvinalexander.com/java/jwarehouse/android-examples/samples/android-9/ApiDemos/tests/src/com/example/android/apis/app/LocalServiceTest.java.shtml) I have tried to copy their code as closely as possible and have had no success.
I theorised that I might need to have the unit test run on a device or an emulator, but this wasn't necessary for my other unit tests that succeeded.
In summary, Why is my attempt to create an intent always returning null?