我有使用Picasso库的代码。
@Inject
public RegistrationPresenter(UserData userData, Picasso picasso) {
this.userData = userData;
this.picasso = picasso;
}
@Override
public void attachView(RegistrationView view) {
super.attachView(view);
view.toggleKeyboardButton(false);
view.showFirstName(userData.getFirstName());
view.showLastName(userData.getLastName());
view.showEmail(userData.getEmail());
setImage();
}
private void setImage() {
String url = String.format(IMAGE_URL, userData.getId());
String tag = String.format(JPG_EXT, userData.getId());
picasso
.load(url)
.tag(tag)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//some actions
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
在我的主持人中,我通过Dagger2提供毕加索
@Provides
@Singleton
Picasso providesPicasso() {
return Picasso.with(context);
}
在我的测试中我使用的是Robolectric和Mockito,所以我嘲笑Picasso并将它传递给presenter的构造函数
@Mock
Picasso picasso;
@Before
public void setUp() {
super.setUp();
MockitoAnnotations.initMocks(this);
mockData = new UserData();
mockData.setFirstName("Name");
mockData.setLastName("LastName");
mockData.setEmail("example@gmail.com");
mockData.setId("123456");
File mockCacheDir = mock(File.class);
Context mockAppContext = mock(Context.class);
when(mockContext.getApplicationContext()).thenReturn(mockAppContext);
when(mockContext.getApplicationContext().getCacheDir()).thenReturn(mockCacheDir);
when(view.getContext()).thenReturn(mockContext);
presenter = new RegistrationPresenter(mockData, picasso);
}
@Test
public void testAttachView() {
presenter.attachView(view); //fails here
verify(view).toggleKeyboardButton(false);
verify(view).showFirstName(mockData.getFirstName());
verify(view).showLastName(mockData.getLastName());
verify(view).showEmail(mockData.getEmail());
}
当我运行我的测试时,它失败并出现异常
java.lang.NullPointerException
at com.squareup.picasso.Utils.createDefaultCacheDir(Utils.java:257)
at com.squareup.picasso.OkHttpDownloader.<init>(OkHttpDownloader.java:45)
at com.squareup.picasso.Utils$OkHttpLoaderCreator.create(Utils.java:424)
at com.squareup.picasso.Utils.createDefaultDownloader(Utils.java:250)
at com.squareup.picasso.Picasso$Builder.build(Picasso.java:832)
at com.squareup.picasso.Picasso.with(Picasso.java:662)
模仿毕加索的正确方法是什么?
答案 0 :(得分:1)
Don't mock File
.您的测试很可能会失败,因为需要实施File
。而是使用TemporaryFolder规则:
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void setUp() {
// ...
when(mockContext.getApplicationContext().getCacheDir()).thenReturn(folder.newFolder()));
// ...
}