Issue
the below posted method in the code section returns void. I want to know how to test a method that returns void. I checked some answers but the use "doThrow()" with passing an exception, but in my case the method does not throw any exception
please let me know how can I test a method returns void?
code
public void setImageOnImageView(RequestCreator requestCreator, ImageView imgView) {
requestCreator.into(imgView);
}
testing:
public class ValidationTest {
@Mock
private Context mCtx = null;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Before
public void setUp() throws Exception {
mCtx = Mockito.mock(Context.class);
Assert.assertNotNull("Context is not null", mCtx);
}
@Test
public void setImageOnImageView() throws Exception {
Uri mockUri = mock(Uri.class);
RequestCreator requestCreator = Picasso.with(mCtx).load(mockUri);
RequestCreator spyRequestCreator = spy(requestCreator);
ImageView imageView = new ImageView(mCtx);
ImageView spyImageView = spy(imageView);
doThrow().when(spyRequestCreator).into(spyImageView);
//spyRequestCreator.into(spyImageView);
}
}
Solution
What exactly are you trying to test? Is that test that "when setImageOnImageView(RequestCreator, ImageView)
is called, it invokes RequestCreator.into(ImageView)
"?
If that's what you're trying to test, you aren't wanting to test that it "returns void". Rather, I would recommend something like:
@Test
public void itInvokesRequestCreatorIntoOnProvidedImageView() {
RequestCreator creator = mock(RequestCreator.class);
ImageView imageView = mock(ImageView.class);
setImageOnImageView(creator, imageView);
verify(creator).into(imageView);
}
Answered By - Kevin Coppock
Answer Checked By - Robin (JavaFixing Admin)