下面代码部分中发布的方法返回 void。我想知道如何测试返回 void 的方法。 我检查了一些答案,但使用“doThrow()”传递异常,但在我的情况下,该方法不会抛出任何异常
请让我知道如何测试方法返回 void?
代码
public void setImageOnImageView(RequestCreator requestCreator, ImageView imgView) {
requestCreator.into(imgView);
}
测试:
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);
}
}
您到底想测试什么?是不是测试“当调用
setImageOnImageView(RequestCreator, ImageView)
时,它会调用 RequestCreator.into(ImageView)
”?
如果这就是您要测试的内容,那么您不想测试它“返回 void”。相反,我会推荐类似的东西:
@Test
public void itInvokesRequestCreatorIntoOnProvidedImageView() {
RequestCreator creator = mock(RequestCreator.class);
ImageView imageView = mock(ImageView.class);
setImageOnImageView(creator, imageView);
verify(creator).into(imageView);
}
如果你想验证一个void方法没有抛出任何东西,那么你可以使用assertDoesNotThrows方法如下
断言所提供的可执行文件的执行不会引发任何类型的异常。 使用注意事项 尽管从测试方法抛出的任何异常都会导致测试失败,但在某些用例中,显式断言测试方法中的给定代码块不会抛出异常是有益的。
Assertions.assertDoesNotThrow(() -> testCl.voidM("test"...));
如果您的类中有一些依赖项,那么您可以使用 verify 来检查该依赖项是否被调用。