我尝试使用TDD并获得以下代码:
public class ViewModel extends BaseObservable {
private final Subscription subscription;
public ReleasesViewModel(Observable<List<Data>> model) {
subscription = model.subscribe(this::setData);
}
public void destroy() { //method is not under test
subscription.unsubscribe();
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
}
和我的测试:
public class ViewModelTest {
@Test
public void getData() {
BehaviorSubject<List<Data>> observable = BehaviorSubject.create();
ViewModel viewModel = new ViewModel(observable);
List<Data> dataList = Arrays.asList(mock(Data.class), mock(Data.class));
observable.onNext(dataList);
assertTrue(viewModel.getData().equals(dataList));
}
}
问题如下:
我应该验证将调用subscription.unsubscribe();
来释放资源,我可以在一些包装器中包装订阅并通过构造函数注入依赖项,但我觉得我可以违反ViewModel
类的封装。经过大量的谷歌搜索后,我没有找到任何线索来验证TDD练习中释放内存的情况。对于这种情况,有人可以指出一些“最佳实践”。
答案 0 :(得分:0)
也许你有一些正确的mvvm测试的例子
这就是我使用Mockito所做的事情(只是我的偏好,任何其他Mocking Framework都会做......):
public class ViewModelTest {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
BehaviorSubject<List<Data>> observable;
@Mock
Subscription subscription;
List<Data> data = Collections.emptyList();
@Test
public void Constructor_CalledWithObservable_subcribesSetDataMethod() {
// prepare
when(model.subscribe()).thenRetun(subscription);
// act
ViewModel viewModel = new ViewModel(observable);
// assert
verify(observable).subscribe(ViewModel::setData);
}
@Test
public void destroy_unsubscribes() {
// prepare
when(model.subscribe()).thenRetun(subscription);
ViewModel viewModel = new ViewModel(observable);
// act
viewModel.destroy();
// assert
verify(subscription).unsubscribe();
}
}