java – 为Presenter类编写Mockito测试(Presenter First Pattern
发布时间:2020-12-15 02:35:21 所属栏目:Java 来源:网络整理
导读:我正在尝试熟悉TDD和Presenter First Pattern.现在我不得不为我的Presenter.class编写一个测试用例.我的目标是覆盖整个Presenter.class,包括动作事件,但我没有胶水如何与Mockito一起做. Presenter.class: public class Presenter {IModel model;IView view;
我正在尝试熟悉TDD和Presenter First Pattern.现在我不得不为我的Presenter.class编写一个测试用例.我的目标是覆盖整个Presenter.class,包括动作事件,但我没有胶水如何与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); } IModel.class: 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() { } } 提前致谢! 解决方法
起初……谢谢你们!
过了一会儿,我想出了这个解决方案并坚持下去,因为我不想在presenter类中实现任何接口,我也不想在我的测试中创建存根类. IVIEW public interface IView { public void setText(String text); } IModel 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()); } }); } } PresenterTest @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"); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |