微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 为Presenter类编写Mockito测试(Presenter First Pattern)

我正在尝试熟悉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");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐