我有使用毕加索库的代码。
@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,所以我模拟毕加索并将其传递给演示者的构造函数。
@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)
嘲笑毕加索的正确方法是什么?
不要嘲笑File
.您的测试很可能失败,因为需要真正的File
实现。请改用临时文件夹规则:
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void setUp() {
// ...
when(mockContext.getApplicationContext().getCacheDir()).thenReturn(folder.newFolder()));
// ...
}