Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't unit test classes that use EventBus #398

Closed
gsteigert opened this issue Feb 7, 2017 · 5 comments
Closed

Can't unit test classes that use EventBus #398

gsteigert opened this issue Feb 7, 2017 · 5 comments

Comments

@gsteigert
Copy link

gsteigert commented Feb 7, 2017

I want to write some unit tests for classes that have their own EventBus instances, but it won't work because EventBus uses Android's Handler in its constructor. Using Otto I'm able to do it, but I want to use EventBus instead. Any ideas?

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

	at android.os.Looper.getMainLooper(Looper.java)
	at org.greenrobot.eventbus.EventBus.<init>(EventBus.java:111)
	at org.greenrobot.eventbus.EventBus.<init>(EventBus.java:104)
	(...)

Process finished with exit code 255
@greenrobot-team
Copy link
Collaborator

You are probably trying to use a local unit test. But as you found out, EventBus depends on some Android features. So you have to use an instrumented unit test that runs on an Android device instead.
-ut

@greenrobot-team greenrobot-team self-assigned this Mar 14, 2017
@gsteigert
Copy link
Author

Ok, thanks!

@greenrobot-team greenrobot-team removed their assignment Apr 11, 2017
@chillbrodev
Copy link

chillbrodev commented Mar 5, 2018

@gsteigert My team and I ran into this exact problem while integrating GreenRobot Eventbus. We wanted to verify that the eventbus was posting a specific event but not the execution of the posted event.

You can achieve this via reflection and mockito mocks.

Java:

Field field = EventBus.class.getDeclaredField("defaultInstance");
if (!field.isAccessible()) field.setAccessible(true);
field.set(null, Mockito.mock(EventBus.class));

Kotlin:

val field = EventBus::class.java.getDeclaredField("defaultInstance")
if (!field.isAccessible) field.isAccessible = true
field.set(null, mock<EventBus>())

@postace
Copy link

postace commented Mar 23, 2018

thank @jmholtan for your answer, it works for me!

@greenrobot-team
Copy link
Collaborator

Note that as of version 3.1.1 EventBus also works for plain-Java projects, so also for Android local unit tests. Though note that some thread modes may behave differently. -ut

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants