Robolectric : Build failed with Null Pointer Exception - android

I recently started to work on the Robolectric unit testing framework for my android apps. I am using Android Studio IDE for this all.
I have made MainActivity.java where there is button R.id.clickButton, I am able to run that app in my phone/emulator and working fine.
I have made MainActivityTest.java where I am trying to see is button not null like below
private MainActivity activity;
#Before
public void setup() {
activity = Robolectric.buildActivity(MainActivity.class).get();
}
#Test
public void shouldFail() {
assertTrue(true);
}
#Test
public void shouldNotBeNull() {
assertThat(activity).isNotNull();
Button button = (Button) activity.findViewById(R.id.clickButton);
assertThat(button).isNotNull();
}
When I execute the test using command line then build failed at Button button = (Button) activity.findViewById(R.id.clickButton); with an error trace. I could not find why it so. Guys look this and hoping you will reply me soon.
StackTrace
java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:132)
at android.view.ViewGroup.initViewGroup(ViewGroup.java:447)
at android.view.ViewGroup.__constructor__(ViewGroup.java:417)
at android.view.ViewGroup.<init>(ViewGroup.java:416)
at android.widget.FrameLayout.<init>(FrameLayout.java:93)
at org.robolectric.tester.android.view.RoboWindow$2.<init>(RoboWindow.java:231)
at org.robolectric.tester.android.view.RoboWindow.createDecorView(RoboWindow.java:231)
at org.robolectric.tester.android.view.RoboWindow.access$000(RoboWindow.java:30)
at org.robolectric.tester.android.view.RoboWindow$1.run(RoboWindow.java:222)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256)
at org.robolectric.tester.android.view.RoboWindow.getDecorView(RoboWindow.java:220)
at org.robolectric.tester.android.view.RoboWindow.findViewById(RoboWindow.java:292)
at org.robolectric.shadows.ShadowActivity.findViewById(ShadowActivity.java:312)
at android.app.Activity.findViewById(Activity.java)
at com.example.robolectrichelloworld.MainActivityTest.shouldNotBeNull(MainActivityTest.java:41)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

Try to insert the call to create() after Robolectric.buildActivity(...):
#Before
public void setup() {
activity = Robolectric.buildActivity(MainActivity.class).create().get();
}

I solved the problem by simply extend the class by Activity. My activity was extending ActionBarActivity that was creating the issue.

Related

Getting Mockito to work with RoboGuice and Robolectric

I am nearly desperate getting Mockito to work in conjunction with RoboGuice and Robolectric.
I have a gradle multiproject which includes an Android app which is designed with RoboGuice. Now I have a test case in which I want to override the default Robuguice modul in order to inject some mocks. But sadly I can not get it working.
Here is my approach so far:
#RunWith(RobolectricTestRunner.class)
public class NetworkUtilTest {
#Inject
private NetworkUtil networkUtil;
private ErrorDialog errorDialog = mock(ErrorDialog.class, Mockito.RETURNS_DEEP_STUBS);
private FragmentActivity activity;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
activity = Robolectric.buildActivity(MainActivity.class).create().get();
RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, Modules.override(RoboGuice.newDefaultRoboModule(Robolectric.application)).with(new MyTestModule()));
RoboInjector injector = RoboGuice.getInjector(activity);
injector.injectMembersWithoutViews(this);
}
#Test
public void testNetworkInfoNull() {
ConnectivityManager manager = (ConnectivityManager) Robolectric.application.getSystemService(Context.CONNECTIVITY_SERVICE);
ShadowConnectivityManager shadowConnectivityManager = shadowOf(manager);
shadowConnectivityManager.setActiveNetworkInfo(null);
networkUtil.isNetworkAvailable();
verify(errorDialog).show(R.string.network_error);
}
private class MyTestModule extends AbstractModule {
#Override
protected void configure() {
bind(ErrorDialog.class).toInstance(errorDialog);
}
}
}
Many instructions are using
RoboGuice.getInjector(Robolectric.application)
but I got tests without the binding of a mock to work with my approach above. So it seems to be the right way?
If I run the test I got the following error:
1) null returned by binding at roboguice.config.DefaultRoboModule.configure(DefaultRoboModule.java:131)
but roboguice.inject.FragmentManagerProvider.activity is not #Nullable
while locating roboguice.inject.NullProvider<android.app.Activity>
at roboguice.config.DefaultRoboModule.configure(DefaultRoboModule.java:131)
while locating android.app.Activity
for field at roboguice.inject.FragmentManagerProvider.activity(Unknown Source)
at roboguice.inject.FragmentManagerProvider.class(Unknown Source)
while locating roboguice.inject.FragmentManagerProvider
while locating android.support.v4.app.FragmentManager
for field at com.example.test.dialog.ErrorDialog.fragmentManager(Unknown Source)
at com.example.test.util.NetworkUtilTest$MyTestModule.configure(NetworkUtilTest.java:80)
1 error
com.google.inject.CreationException: Guice creation errors:
1) null returned by binding at roboguice.config.DefaultRoboModule.configure(DefaultRoboModule.java:131)
but roboguice.inject.FragmentManagerProvider.activity is not #Nullable
while locating roboguice.inject.NullProvider<android.app.Activity>
at roboguice.config.DefaultRoboModule.configure(DefaultRoboModule.java:131)
while locating android.app.Activity
for field at roboguice.inject.FragmentManagerProvider.activity(Unknown Source)
at roboguice.inject.FragmentManagerProvider.class(Unknown Source)
while locating roboguice.inject.FragmentManagerProvider
while locating android.support.v4.app.FragmentManager
for field at com.example.test.dialog.ErrorDialog.fragmentManager(Unknown Source)
at com.example.test.util.NetworkUtilTest$MyTestModule.configure(NetworkUtilTest.java:80)
1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:435)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:175)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:109)
at com.google.inject.Guice.createInjector(Guice.java:95)
at com.google.inject.Guice.createInjector(Guice.java:83)
at roboguice.RoboGuice.setBaseApplicationInjector(RoboGuice.java:94)
at com.example.test.util.NetworkUtilTest.setUp(NetworkUtilTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at $Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Does anybody know a solution for this problem? There are many guides for advanced Android testing with Mockito, RoboGuice and Robolectric, so I think that is has to work?
I already took a look at the astroboy examples, but it did not get me further.
Regards
Tobias
Thank you for your answers!
I finally fixed it by adding the following line to my test module:
bind(FragmentManager.class).toInstance(activity.getSupportFragmentManager());
Then the tests run successfully. I hope that there are no additional problems. I wasted enough time :-)

Robolectric tests fail on ContextCompat.getExternalFilesDirs

in my app I'm calling ContextCompat.getExternalFilesDirs and my Robolectric test fails with the following stacktrace:
java.lang.NoSuchMethodError: android.content.Context.getExternalFilesDirs(Ljava/lang/String;)[Ljava/io/File;
at android.support.v4.content.ContextCompatKitKat.getExternalFilesDirs(ContextCompatKitKat.java:29)
at android.support.v4.content.ContextCompat.getExternalFilesDirs(ContextCompat.java:216)
at com.mondiamedia.mmplaylistapp.helpers.SongFileHelper.getMyPlaylistSongsFolder(SongFileHelper.java:73)
at com.mondiamedia.mmplaylistapp.helpers.SongFileHelper.getNewMyPlaylistSongFile(SongFileHelper.java:48)
at com.mondiamedia.mmplaylistapp.helpers.SongFileHelperTest.testGetNewMyPlaylistSongFileWithValidSong(SongFileHelperTest.java:60)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I looked at the ContextCompat.java and the culprit seems to be this part:
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
return ContextCompatKitKat.getExternalFilesDirs(context, type);
} else {
final File single;
if (version >= 8) {
single = ContextCompatFroyo.getExternalFilesDir(context, type);
In the test I put #Config(emulateSdk = 18) but it seems that Robolectric still runs it as SDK 19 so the ContextCompatKitKat class gets called. Does anyone have any idea how to prevent this error? The obvious solution would be to call ContextCompatFroyo but I don't know if there are any unwanted side effects.

Android Testing with Robolectric ClassCastException: android.app.Application cannot be cast to MyApplication

I'm testing my android App with Robolectric and I'm struggling with this cast :
MyModel myModel = ((MyApplication) context.getApplicationContext()).getMyModel;
Apparently Robolectric is complaining with this error:
java.lang.RuntimeException: java.lang.ClassCastException: android.app.Application cannot be cast to com.reply.delhaize.common.DelhaizeApplication
at org.robolectric.util.SimpleFuture.run(SimpleFuture.java:57)
at org.robolectric.shadows.ShadowAsyncTask$2.run(ShadowAsyncTask.java:95)
at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:37)
at org.robolectric.util.Scheduler.post(Scheduler.java:42)
at org.robolectric.shadows.ShadowAsyncTask.execute(ShadowAsyncTask.java:92)
at android.os.AsyncTask.execute(AsyncTask.java)
at com.reply.delhaize.common.models.StoreModel.getStoreList(StoreModel.java:617)
at com.reply.delhaize.common.models.StoreModel.fetchAllStores(StoreModel.java:107)
at com.reply.delhaize.core.tests.storefinder.StoreFinderTest.fetchAllStoresWhenWifiIsOn(StoreFinderTest.java:84)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:234)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:175)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.reply.delhaize.common.DelhaizeApplication
at com.my.package.name.models.GetApiModelTaskOtto.doInBackground(GetApiModelTaskOtto.java:74)
at com.my.package.name.models.GetApiModelTaskOtto.doInBackground(GetApiModelTaskOtto.java:1)
at android.os.ShadowAsyncTaskBridge.doInBackground(ShadowAsyncTaskBridge.java:14)
at org.robolectric.shadows.ShadowAsyncTask$BackgroundWorker.call(ShadowAsyncTask.java:149)
at org.robolectric.util.SimpleFuture.run(SimpleFuture.java:52)
at org.robolectric.shadows.ShadowAsyncTask$2.run(ShadowAsyncTask.java:95)
at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:37)
at org.robolectric.util.Scheduler.post(Scheduler.java:42)
at org.robolectric.shadows.ShadowAsyncTask.execute(ShadowAsyncTask.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.robolectric.bytecode.ShadowWrangler$ShadowMethodPlan.run(ShadowWrangler.java:456)
at android.os.AsyncTask.execute(AsyncTask.java)
at com.my.package.name.models.StoreModel.getStoreList(StoreModel.java:617)
at com.my.package.name.models.StoreModel.fetchAllStores(StoreModel.java:107)
at com.reply.delhaize.core.tests.storefinder.StoreFinderTest.fetchAllStoresWhenWifiIsOn(StoreFinderTest.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
... 22 more
I would like to find a proper way to test it.
I have declared MyApplication in the manifest:
<application
android:name="com.my.package.name.MyApplication"
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
......
and these are the tests
#RunWith(RoboletricTestRunner.class)
public class StoreFinderTest extends BaseTest {
StoreListActivity storeListActivity;
StoreModel storeModel;
UserModel userModel;
#Before
public void setUp() throws Exception {
storeListActivity = Robolectric.buildActivity(StoreListActivity.class).get();
storeModel = new StoreModel(storeListActivity.getApplicationContext());
userModel = new UserModel(storeListActivity.getApplicationContext());
}
#Test
public void activityExists() {
assertThat(storeListActivity).isNotNull();
}
#Test
public void fetchAllStoresWhenWifiIsOn() {
ConnectivityManager cm =(ConnectivityManager)Robolectric.application.getSystemService(Context.CONNECTIVITY_SERVICE);
Robolectric.shadowOf(cm).setNetworkInfo(ConnectivityManager.TYPE_WIFI, cm.getActiveNetworkInfo());
boolean result = storeModel.fetchAllStores();
assertTrue(result);
}
storeModel.fetchAllStores() implementation has this ugly cast:
MyModel myModel = ((MyApplication) context.getApplicationContext()).getMyModel;
So is there a way for testing with Robolectric portion of code that contains cast like this ?
((MyApplication) context.getApplicationContext())
You may need to specify the path to your AndroidManifest.xml for your test. You can do so using as follows:
#Config(manifest = "/path/to/your/AndroidManifest.xml")
#RunWith(RoboletricTestRunner.class)
public class StoreFinderTest extends BaseTest {
...
}
You can make Robolectric use a test version of your application by simply creating a TestMyApplication class (i.e. class with prefix "Test" before the name of your application class) in the same package as your MyApplication in the test directory of your project. To work around your casting problem, TestMyApplication should extend MyApplication:
public class TestMyApplication extends MyApplication {
}
Encountered the same error;
java.lang.ClassCastException: androidx.test.runner.AndroidJUnitRunner cannot be cast to org.robolectric.android.fakes.RoboMonitoringInstrumentation
I realized I was using the wrong implementation for Roboelectric:
implementation "org.robolectric:robolectric:4.5.1"
If you are using this please replace it with testImplementation instead:
testImplementation "org.robolectric:robolectric:$robolectricVersion"
I don't know Robolectric but maybe add an
if(context.getApplicationContext() instanceof MyApplication
statement

Robolectric & Junit

I am getting the following exception while trying to run tests with robolectric on eclipse. Stumped what is causing this issue. Anyone faced the same?
My test class has only the following. I am just starting on it.
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
#RunWith(RobolectricTestRunner.class)
public class ABCMainActivityTest {
#Test
public void shouldFail() {
assertTrue(true);
}
}
Getting the following exception when i execute with the argument -noverify
java.lang.IllegalArgumentException: Test class can only have one constructor
at org.junit.runners.model.TestClass.<init>(TestClass.java:37)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.robolectric.RobolectricTestRunner$HelperTestRunner.<init>(RobolectricTestRunner.java:643)
at org.robolectric.RobolectricTestRunner.getHelperTestRunner(RobolectricTestRunner.java:261)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:194)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:175)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
else if i am not passing any arguments i am getting a
java.lang.VerifyError: Expecting a stackmap frame at branch target 46

Robolectric: Error Inflating Layout when adding button to the layout.xml

I'm using Robolectric version 1.1 and it can't run my test if there is a button in the activity.
add_emoticon_activity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="#+id/addEmoticonButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/add_emoticon_button_text"
/>
</LinearLayout>
AddEmoticonActivity.java
import android.app.Activity;
import android.os.Bundle;
public class AddEmoticonActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_emoticon_activity);
}
}
AddEmoticonActivityTest.java
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.widget.Button;
import com.xtremelabs.robolectric.RobolectricTestRunner;
import com.xtremelabs.robolectric.shadows.ShadowHandler;
import com.xtremelabs.robolectric.shadows.ShadowToast;
#RunWith(RobolectricTestRunner.class)
public class AddEmoticonActivityTest {
private AddEmoticonActivity addEmoticonActivity;
private Button addButton;
#Before
public void setup() {
addEmoticonActivity = new AddEmoticonActivity();
addEmoticonActivity.onCreate(null);
addButton = (Button) addEmoticonActivity.findViewById(R.id.addEmoticonButton);
}
#Test
public void shouldDisplayErrorMessageWhenEmptyContentAdded() {
addButton.performClick();
ShadowHandler.idleMainLooper();
assertThat(ShadowToast.getTextOfLatestToast(), equalTo(addEmoticonActivity.getResources().getString(R.string.no_content_error_message)));
}
}
Below is the stacktrace that I got when I ran the test
java.lang.RuntimeException: error inflating layout/add_emoticon_activity
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:106)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:82)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:86)
at com.xtremelabs.robolectric.res.ResourceLoader.inflateView(ResourceLoader.java:377)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:43)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:48)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at com.xtremelabs.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:101)
at android.app.Activity.setContentView(Activity.java)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivity.onCreate(AddEmoticonActivity.java:10)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivityTest.setup(AddEmoticonActivityTest.java:24)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at com.xtremelabs.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:292)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.constructView(ViewLoader.java:228)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.create(ViewLoader.java:179)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.inflate(ViewLoader.java:150)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.inflate(ViewLoader.java:153)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:102)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:82)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:86)
at com.xtremelabs.robolectric.res.ResourceLoader.inflateView(ResourceLoader.java:377)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:43)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.xtremelabs.robolectric.bytecode.ShadowWrangler.methodInvoked(ShadowWrangler.java:99)
at com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(RobolectricInternals.java:111)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at com.xtremelabs.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.xtremelabs.robolectric.bytecode.ShadowWrangler.methodInvoked(ShadowWrangler.java:99)
at com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(RobolectricInternals.java:111)
at android.app.Activity.setContentView(Activity.java)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivity.onCreate(AddEmoticonActivity.java:10)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivityTest.setup(AddEmoticonActivityTest.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
... 20 more
Caused by: java.lang.NullPointerException
at com.xtremelabs.robolectric.res.ColorResourceLoader.getValue(ColorResourceLoader.java:33)
at com.xtremelabs.robolectric.res.ResourceLoader.getColorValue(ResourceLoader.java:382)
at com.xtremelabs.robolectric.shadows.ShadowResources.getColor(ShadowResources.java:65)
at android.content.res.Resources.getColor(Resources.java)
at com.xtremelabs.robolectric.shadows.ShadowView.setBackgroundColor(ShadowView.java:243)
at com.xtremelabs.robolectric.shadows.ShadowButton.applyAttributes(ShadowButton.java:14)
at com.xtremelabs.robolectric.shadows.ShadowView.__constructor__(ShadowView.java:90)
at com.xtremelabs.robolectric.shadows.ShadowView.__constructor__(ShadowView.java:82)
at android.widget.Button.<init>(Button.java)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.constructView(ViewLoader.java:228)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.create(ViewLoader.java:179)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.inflate(ViewLoader.java:150)
at com.xtremelabs.robolectric.res.ViewLoader$ViewNode.inflate(ViewLoader.java:153)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:102)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:82)
at com.xtremelabs.robolectric.res.ViewLoader.inflateView(ViewLoader.java:86)
at com.xtremelabs.robolectric.res.ResourceLoader.inflateView(ResourceLoader.java:377)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:43)
at com.xtremelabs.robolectric.shadows.ShadowLayoutInflater.inflate(ShadowLayoutInflater.java:48)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at com.xtremelabs.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:101)
at android.app.Activity.setContentView(Activity.java)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivity.onCreate(AddEmoticonActivity.java:10)
at com.erlanggatjhie.emotextcon.activities.AddEmoticonActivityTest.setup(AddEmoticonActivityTest.java:24)
... 20 more
If I remove the button from layout.xml, it will work beautifully.
Does anyone know what happened?
Thanks a lot
It looks like it all comes down the a NullPointerException that caused the original problem.
This commit happened after 1.1 was released and it changed line 33 of the ColorResourceLoader.java, which is the line where you received the error.
https://github.com/pivotal/robolectric/commit/f647512bd80162f9cb6b2fac8c7b0db984266967
It looks like if you upgrade to a newer version of Robolectric it may fix the problem. I know 1.1 is the latest release version, but there is a 2.0 alpha 1 version that is out.

Categories

Resources