5

I want to test a method in a fragment but in this method I call a Toast:

Toast.makeText(getActivity(), getString(R.string.signs), Toast.LENGTH_SHORT).show();

Now I want to test the method with JUnit and Powermockito. For this I want to ignore the Toast. I tried it like this: mock the Toast and ignor toast.show()

Toast toastMock = mock(Toast.class);
doReturn(toastMock).when(Toast.makeText(any(Activity.class), anyString(), Toast.LENGTH_SHORT));
doNothing().when(toastMock).show();

But I always get a RuntimeException, because I call Toast without creating a new toast object. How can I bypass this problem?

R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
  • can you add full test case? with PowerMockito setup as well – Maciej Kowalski Mar 07 '17 at 11:46
  • You're trying to mock a static method, you'll either have to wrap the static call into a non-static class which you can then mock, or mock the static method for which you can find help here http://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object – zsmb13 Mar 07 '17 at 11:48

1 Answers1

0

Write external class with method responsible for showing Toast, inject it to a fragment and mock this class behaviour. It might be a static method, as you use PowerMockito.

How to inject? Use Dagger or Toothpick.

R. Zagórski
  • 20,020
  • 5
  • 65
  • 90