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");
    }
}

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...