5

I'm trying to build a valid junit testing suite on android.

Since i'm new to Junit i can't figure out how to use the ServiceTestCase class.

I can't figure it out how to get the getService() method working. it ever returns me null . So i decided to start it via startService. It does not work.

Could you please help me ?

Thanks

prolink007
  • 33,872
  • 24
  • 117
  • 185
Andrea Baccega
  • 27,211
  • 13
  • 45
  • 46
  • 1
    If someone answers your question it is customary to click the check mark next to their answer. Doing this will help you to get better answers faster. – Thomas Dignan Jun 05 '11 at 08:23

2 Answers2

16

This is what you need to test your service

public class MyServiceTests extends ServiceTestCase<MyService> {

private static final String TAG = "MyServiceTests";

public MyServiceTests() {
    super(MyService.class);
}

/**
 * Test basic startup/shutdown of Service
 */
@SmallTest
public void testStartable() {
    Intent startIntent = new Intent();
    startIntent.setClass(getContext(), MyService.class);
    startService(startIntent);
    assertNotNull(getService());
}

/**
 * Test binding to service
 */
@MediumTest
public void testBindable() {
    Intent startIntent = new Intent();
    startIntent.setClass(getContext(), MyService.class);
    IBinder service = bindService(startIntent);
    assertNotNull(service);
}
}

I've written some articles about Android testing and test driven development that you may find useful, check http://dtmilano.blogspot.com/search/label/test%20driven%20development.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

The accepted answer doesn't work any more.

TestCases like ActivityInstrumentationTestCase2 or ServiceTestCase are deprecated in favor of ActivityTestRule or ServiceTestRule.

ATSL link

It seems they forgot to update the actual documentation.

Herrbert74
  • 2,578
  • 31
  • 51