我正在尝试为AlbumsController
创建一个测试用例,以从网络中获取数据并进行解析。
AlbumService
:负责网络通话和获取数据。 (假定它可以是执行某些异步任务并相应地提供回调的任何事物,以避免使用“服务器”特定的模拟解决方案)
public class AlbumsController {
public void getAlbums(final ServiceCallback<AlbumsWrapper> albumsServiceCallback) {
new AlbumsService().fetchAlbums(new ServiceCallback<NetworkResponse>() {
@Override
public void onSuccess(NetworkResponse response) {
// parse response
}
@Override
public void onFailure(NetworkResponse error) {
// do something for Failure
}
});
}
public class AlbumControllerTest {
@Mock
private ServiceCallback<NetworkResponse> serviceCallback;
@Captor
private ArgumentCaptor<ServiceCallback<AlbumsWrapper>> albumsWrapper;
@Captor
private ArgumentCaptor<ServiceCallback<NetworkResponse>> networkResponseArgumentCaptor;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void parseAlbums_EmptyList_ReturnsTrue() {
// below are different ways I am trying with no success so far.
AlbumsController albumsController = new AlbumsController();
albumsController.getAlbums(albumsWrapper.capture());
NetworkResponse response = new NetworkResponse();
networkResponseArgumentCaptor.capture();
networkResponseArgumentCaptor.getValue().onSuccess(response);
}
}
目标:
getAlbums
方法中模拟AlbumService,以便代替从服务器获取数据,我应该能够使用测试数据作为参数来调用onSuccess()
。解析后是否可以获得列表,以便我可以assert
基于列表中的数据?图书馆
答案 0 :(得分:0)
如果选择小的重构,则:
1):将new AlbumsService()
移至包级方法:
AlbumService createAlbumService(){
return new AlbumService();
}
...
public void getAlbums(final ServiceCallback<AlbumsWrapper> albumsServiceCallback) {
createAlbumService().fetchAlbums(new ServiceCallback<NetworkResponse>()
package
的可见性已足够,因为测试类将与AlbumController
放在同一包中。
2)监视AlbumController
:
@Spy
private AlbumsController albumsControllerSpy = new AlbumController();
@Mock
private AlbumService albumServiceMock;
3)使createAlbumService()
方法返回您的模拟:
@Test
public void parseAlbums_EmptyList_ReturnsTrue() {
doReturn(albumServiceMock).when(albumControllerSpy).createAlbumService();
...