Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android BluetoothAdapter Mocking

I'm trying to mock test Bluetooth application but my first step of creating a mock object of BluetoothAdapter class is not working!!

I'm using powermockito with easy mock.

 mBluetoothAdapter = (BluetoothAdapter)PowerMock.createMock(BluetoothAdapter.class);

this fails. with the following stack trace

java.lang.IllegalArgumentException: No visible constructors in class android.bluetooth.BluetoothAdapter
at org.easymock.internal.DefaultClassInstantiator.getConstructorToUse(DefaultClassInstantiator.java:94)
at org.easymock.internal.AndroidClassProxyFactory.createProxy(AndroidClassProxyFactory.java:48)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:114)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:88)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:79)
at org.powermock.api.easymock.PowerMock.doCreateMock(PowerMock.java:2212)
at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2163)
at org.powermock.api.easymock.PowerMock.createMock(PowerMock.java:89)
at com.xxx.blesimplesample.test.MainActivityTest.setUp(MainActivityTest.java:59)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1710)

Any one has used any mocking framework for Bluetooth app mocking? Any suggestions will be v helpful

like image 406
Ramya K Sharma Avatar asked Nov 04 '14 09:11

Ramya K Sharma


1 Answers

BluetoothAdapter in the Android framework is declared final, so at the time you asked this question, it couldn't be mocked, neither with Mockito nor using Robolectric.

However, Android unit testing has changed a lot since then. With recent versions of the tools, when you build unit tests the tools generate a patched android.jar with all the finals removed. This makes all Android classes available for mocking. Nowadays, if you want to mock any Bluetooth code, you can do so in the standard way. The code you've already tried will "just work" if you update to the latest tools. Alternatively, Robolectric has a ShadowBluetoothAdapter class built in now.

like image 190
Dan Hulme Avatar answered Nov 09 '22 18:11

Dan Hulme