以下是我如何做我的 MVP。
除了让我的演示者在我的视图中调用 getter 之外,我的视图调用了我的演示者的方法。通过这种方式,业务逻辑与演示者隔离,并且无需模拟视图即可轻松测试。
public interface MyView extends View {
void setObjectsList(List<Object> objects);
void setPresenter(Presenter presenter);
interface Presenter {
void handleObjectSelected(Object object);
}
}
Presenter 实现 MyView.Presenter:
class MyPresenter implements MyView.Presenter {
private final MyView myView;
private List<Object> objects;
public MyPresenter(MyView myView, List<Objects> objects) {
this.myView = myView;
this.objects = objects;
}
public void initialize() {
myView.setPresenter(this);
myView.setObjectsList(objects);
}
@Override
public void handleObjectSelected(Object object) {
// Do something with selected object.
}
}
示例 MyView 实现:
class MyViewImpl implements MyView {
private Presenter presenter;
...
@Override
public void setObjectsList(List<Object> objects) {
// Do something with object list.
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public void somethingHappened() {
presenter.handleObjectSelected(object);
}
}
使用 ListBox 的 MyView 的第二个实现示例:
class ListBoxMyViewImpl implements MyView {
@UiField ListBox listBox;
private Presenter presenter;
private List<Object> objects;
public MyListBoxView() {
objects = Lists.newArrayLists();
}
@Override
public void setObjectsList(List<Object> objects) {
this.objects = objects;
listBox.clear();
for (Object object : objects) {
listBox.addItem(object.toString());
}
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
@UiHandler("listBox")
void onChange(ChangeEvent e) {
presenter.handleObjectSelected(objects.get(listBox.getSelectedIndex());
}
...
}
这样您就不需要模拟您的视图来测试演示者逻辑。
代替:
@Mock
MyView view;
List testValues = ...;
when(view.getValues().getValues()).thenReturn(testValues);
result = presenter.method(...);
assertTrue(result == expected);
您将测试您的演示者逻辑:
List testValues = ...;
assertEquals(expected, presenter.method(testValues));