Asher
Asher

Reputation: 53

Use Robolectric to test BluetoothAdapter in android 4.3

In my android app, there the following code:

BluetoothManager bm = (BluetoothManager)activity.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter ba = bm.getAdapter();

I want to do Unit Tests using Robolectric. I am using Robolectric 2.2. But I found that bm is null, and I don't know how to mock it.

Upvotes: 4

Views: 1395

Answers (1)

Hans Cappelle
Hans Cappelle

Reputation: 17495

The challenge

The challenge with testing for bluetooth and other system services is that these classes are all final.

The hard way (skip and go to powermock solution if you like)

So if you want to inject anything else you need to make a wrapper around the final class and then provide an implementation forwarding to actual bluetooth classes and an alternative one that mocks your stuff. But then all coded needs to be updated to use that wrapper instead of the final classes directly.

PowerMock solution

PowerMock however should be able to handle these final classes. The summary (follow link for more detail)

  • Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
  • Use the @PrepareForTest(ClassWithFinal.class) annotation at the class-level of the test case.
  • Use PowerMock.createMock(ClassWithFinal.class) to create a mock object for all methods of this class (let's call it mockObject).
  • Use PowerMock.replay(mockObject) to change the mock object to replay mode.
  • Use PowerMock.verify(mockObject) to change the mock object to verify mode.

Upvotes: 1

Related Questions