我正在尝试熟悉 TDD 和 Presenter First 模式。现在我一直在为我的 Presenter.class 编写测试用例。我的目标是覆盖整个 Presenter.class,包括 Action Event,但我不知道如何使用 Mockito 来实现。
Presenter.class:
public class Presenter {
IModel model;
IView view;
public Presenter(final IModel model, final IView view) {
this.model = model;
this.view = view;
this.model.addModelChangesListener(new AbstractAction() {
public void actionPerformed(ActionEvent arg0) {
view.setText(model.getText());
}
});
}}
IView.class:
public interface IView {
public void setText(String text);
}
模型类:
public interface IModel {
public void setText();
public String getText();
public void whenModelChanges();
public void addModelChangesListener(AbstractAction action);
}
PresenterTest.class:
@RunWith(MockitoJUnitRunner.class)
public class PresenterTest {
@Mock
IView view;
@Mock
IModel model;
@Before
public void setup() {
new Presenter(model, view);
}
@Test
public void test1() {
}
}
提前致谢!
最佳答案
首先……谢谢你们!
一段时间后,我想出了这个解决方案并坚持使用它,因为我不想在演示者类中实现任何接口(interface),也不想在我的测试中创建 stub 类。
我看
public interface IView {
public void setText(String text);
}
模型
public interface IModel {
public String getText();
public void addModelChangeListener(Action a);
}
主持人
public class Presenter {
private IModel model;
private IView view;
public Presenter(final IModel model, final IView view) {
this.model = model;
this.view = view;
model.addModelChangeListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
view.setText(model.getText());
}
});
}
}
演示者测试
@RunWith(MockitoJUnitRunner.class)
public class PresenterTest {
@Mock
IView view;
@Mock
IModel model;
@Test
public void when_model_changes_presenter_should_update_view() {
ArgumentCaptor<Action> event = ArgumentCaptor.forClass(Action.class);
when(model.getText()).thenReturn("test-string");
new Presenter(model, view);
verify(model).addModelChangeListener(event.capture());
event.getValue().actionPerformed(null);
verify(view).setText("test-string");
}
}
关于java - 为 Presenter 类编写 Mockito 测试(Presenter First 模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11286269/