Mocking getActivity when testing a Fragment

1,444 views
Skip to first unread message

VRS

unread,
Aug 19, 2013, 8:21:40 AM8/19/13
to moc...@googlegroups.com
Hello everybody

I want to test a method of a Fragment, and inside that method I have a call to getActivity().getPackageManager()  but I am getting a NullPointerException because getActivity is null.
I can´t change the code of that class, but I would like to know how to mock that call to getActivity()   (getActivity belongs to FragmentActivity)

Thanks in advance

Eric Lefevre-Ardant

unread,
Aug 19, 2013, 8:33:07 AM8/19/13
to moc...@googlegroups.com
Does your Fragment have a setActivity() or otherwise allow you to pass your own instance of Activity (maybe to the constructor)?

Mockito does not allow you to mock "calls" by themselves. It allows you to mock instances and then specify a behavior for the methods of that instance.



--
You received this message because you are subscribed to the Google Groups "mockito" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mockito+u...@googlegroups.com.
To post to this group, send email to moc...@googlegroups.com.
Visit this group at http://groups.google.com/group/mockito.
For more options, visit https://groups.google.com/groups/opt_out.

David Wallace

unread,
Aug 19, 2013, 3:06:29 PM8/19/13
to moc...@googlegroups.com
Hi VRS,
I'm not sure if I've understood you correctly; but if getActivity is a method of the FragmentActivity class, then  you'll want a mock instance of FragmentActivity; then you'll need to find some way of injecting that mock instance into your Fragment instance, so that the mock is used for the call to getActivity.  Without seeing  your code, it's hard to comment on how to do this.  Is there a setter you can use?  Or a constructor that has a FragmentActivity as one parameter?  

Regards,
David.


--

VRS

unread,
Sep 5, 2013, 5:26:18 AM9/5/13
to moc...@googlegroups.com
Hello,

Finally, the only way that I had is to set the value to the attribute using reflection, because I didn´t have a set method and I am not allowed to add code.  
Because I saw that I can´t override getActivity(), and I can´t mock that method neither.
Reply all
Reply to author
Forward
0 new messages