我使用Retrofit从服务器下载用户的帖子,并将信息放入Recycler View。下载在演示者类中实现,回收器视图位于活动中。我想通过模拟我的Web服务测试成功响应后Recycler View的适配器是否改变了它的大小。这样做的正确方法是什么?
的活动:
Cats.meow?
主讲人:
public class MainActivity extends AppCompatActivity {
@Inject
MainActivityPresenter presenter;
@BindView(R.id.postsRecView)
RecyclerView postsRecView;
private PostAdapter postAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//bind views
ButterKnife.bind(this);
//action bar
setSupportActionBar(toolbar);
//get dependencies
((MainApp)getApplication()).getFragmentComponent().inject(this);
((MainApp)getApplication()).getWebServiceComponent().inject(this);
//set up presenter
presenter.setActivity(this);
//when activity created, set up web service communication and download posts
presenter.setDefaultWebService();
presenter.downloadPostsList();
}
/**
* Sets elements (posts) to recycler view list.
*/
public void setUpList(List<Post> posts) {
postsRecView.setHasFixedSize(true);
postsRecView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
postsRecView.setItemAnimator(new DefaultItemAnimator());
this.postAdapter = new PostAdapter(posts, postsRecView);
postsRecView.setAdapter(postAdapter);
}
/**
* Returns adapter of posts.
* @return PostAdapter
*/
public PostAdapter getAdapter(){
return postAdapter;
}
}
网络服务:
public class MainActivityPresenter {
private MainActivity activity;
private WebService service;
@Inject
Retrofit retrofit;
private List<Post> posts = new ArrayList<>();
private static final String TAG = "MYAPP";
private static final String TAG_FAIL = "FAIL";
/**
* Constructor.
*/
@Inject
public MainActivityPresenter (){
}
/**
* Sets activity.
* @param activity
*/
public void setActivity(MainActivity activity) {
this.activity = activity;
}
/**
* Sets default web service.
* @return WebService
*/
public WebService setDefaultWebService(){
WebService service = retrofit.create(WebService.class);
this.service = service;
return service;
}
/**
* Sets web service.
* @param service
*/
public void setWebService(WebService service) {
this.service = service;
}
/**
* Downloads posts and asks the activity to create list of them.
*/
public void downloadPostsList(){
posts.clear();
//get new elements
service.getData().enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
//assign response objects to list
posts = response.body();
//send list objects to the list of activity
activity.setUpList(posts);
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Log.d(TAG, TAG_FAIL);
}
});
}
public WebService getService(){
return service;
}
}
目前,我的测试类看起来像这样,但是它会在测试的第一行抛出空指针异常:
public interface WebService {
@GET("/users.php")
Call<List<Post>> getData();
}