【发布时间】:2018-02-26 20:28:34
【问题描述】:
以下代码部分中发布的方法包含一个静态方法,即“with()”。我想测试下面的代码,所以我编写了这个方法的测试 如测试部分所示。
我尝试同时使用“spy()”和“mock()”测试该方法,但测试总是失败。
请告诉我如何测试方法返回 void?
代码
public RequestCreator requestCreatorFromUrl(String picUrl) {
return Picasso.with(mCtx).load(picUrl);
}
测试:
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 whenRequestCreatorFromUrlTest() throws Exception {
Picasso picasso = Picasso.with(mCtx);
Picasso spyPicasso = spy(picasso);
Uri mockUri = mock(Uri.class);
RequestCreator requestCreator = Picasso.with(mCtx).load(mockUri);
RequestCreator spyRequestCreator = spy(requestCreator);
doReturn(spyRequestCreator).when(spyPicasso.load(mockUri));
//when(spyPicasso.load(mockUri)).thenReturn(spyRequestCreator);
RequestCreator actual = spyPicasso.load(mockUri);
Assert.assertEquals(requestCreator, actual);
}
【问题讨论】:
-
当然:默认答案是 - 如果可能,将您的生产代码更改为不需要模拟静态方法。
-
@GhostCat,同意,尽可能避免模拟静态方法的需要。但是 Letsamrit 在下面的 cmets 中写道,因为 Picasso 类来自我正在使用的外部库。我认为在这种情况下,模拟静态的东西是必要的。
-
@mxf 取决于您愿意投入多少努力。你可以总是创建你自己的interface来包裹这些功能。然后你提供一个小的 impl 类,它只调用静态的东西。这也有助于您从外部库中去耦合您的逻辑。
-
@GhostCat,谢谢,很好的解决方案。
-
@mxf 当然 ;-) ...而且很可能,您会找到我的答案之一...已经在某个地方准确地说出来了。
标签: android unit-testing junit mockito powermockito