我正在尝试为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);
}
}
aim:
- 要模拟
getAlbums
方法中的相册服务,这样,就不应该从服务器中获取数据,我应该能够将onSuccess()
用我的测试数据作为参数调用。解析后是否可以获取列表,以便我可以在列表中的数据上进行assert
? - 我不想将负责解析的代码移动到某种方法并公开。我的目的是了解如何处理这种情况。
- 如果需要在TDD中照顾的情况下,则开放代码。
- 全面解决方案或指示都可以寻找两者。
库
- Mockito-core:2.2.9
- junit:4.12
如果小重构是选项,则:
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();
...