Reputation: 1
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);
}
}
Upvotes: 4
Views: 7598
Reputation: 6333
If you want to verify a void method is not throwing anything, then you can use the assertDoesNotThrows method as follow
Assert that execution of the supplied executable does not throw any kind of exception. Usage Note Although any exception thrown from a test method will cause the test to fail, there are certain use cases where it can be beneficial to explicitly assert that an exception is not thrown for a given code block within a test method.
Assertions.assertDoesNotThrow(() -> testCl.voidM("test"...));
If you have some dependencies in your class then you can use verify to check whether that dependency is invoked or not.
Upvotes: 1
Reputation: 134664
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);
}
Upvotes: 2