很抱歉,我的问题很傻,我是Android studio中的测试新手,无法在网上找到解决方案。我想验证是否每当presenter中的方法被调用时,视图中的方法就会被调用。
@Override
public void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
view.galleryImageSelected(intent);
}
上面的片段是我的Presenter类中的一个方法,正如你所看到的那样,我从这个函数中调用了view的一个接口方法.现在我必须验证这个片段是否完美地工作。
@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {
@Mock
private File storageDir;
@Mock
private PackageManager pManager;
@Mock
private Context appContext;
@Mock
private MainActivityContract.View view;
@InjectMocks
private MainActivityPresenter presenter;
@Captor
private ArgumentCaptor<Intent> captor;
@Before
public void setUp() throws Exception {
presenter = new MainActivityPresenter(storageDir, pManager, appContext, view);
}
@Test
public void shouldCallIntentWhenClickedOnCameraClickButton() throws IOException {
presenter.chooseImage();
verify(view).galleryImageSelected(captor.capture());
Intent intent = captor.getValue();
String action = intent.getAction();
String type = intent.getType();
assertThat(action, is(Intent.ACTION_GET_CONTENT));
assertThat(type, is("image/*"));
}
}
现在为了验证view的方法,我必须在galleryImageSelected()方法中传递intent,但是由于intent是一个本地变量,我如何测试?我是否必须先模拟变量intent,然后再传递,如果是,如何模拟一个intent变量。
另外如果我在做下面的事情。
@Test
public void shouldCallIntentWhenClickedOnCameraClickButton() throws IOException {
presenter.chooseImage();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
verify(view).galleryImageSelected(intent);
}
我在测试时得到以下错误信息
Argument(s) are different! Wanted:
view.galleryImageSelected(null);
-> at com.example.imagepicker.ExampleUnitTest.shouldCallIntentWhenClickedOnCameraClickButton(ExampleUnitTest.java:52)
Actual invocation has different arguments:
你不能模拟本地变量,但你可以捕获传递的参数,使用的是 ArgumentCaptor 然后将论点验证为
@RunWith(MockitoJUnitRunner.class)
public class PresenterTest {
@Mock
private View view;
@InjectMocks
private Presenter presenter;
@Captor
private ArgumentCaptor<Intent> captor;
@Test
public void shouldCallIntentWhenClickedOnCameraClickButton() {
presenter.chooseImage();
verify(view).galleryImageSelected(captor.capture());
Intent intent = captor.getValue();
String action = intent.getAction();
String type = intent.getType();
assertThat(action, is(Intent.ACTION_GET_CONTENT));
assertThat(type, is("image/*"));
}
}