java - 为 Presenter 类编写 Mockito 测试(Presenter First 模式)

标签 java unit-testing design-patterns mockito presenter-first

我正在尝试熟悉 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/

相关文章:

Java奇数屏幕位置

php - 模拟数据库查询 laravel mock

unit-testing - NUnit 和 Log4Net 集成 : asserting based on the log

unit-testing - 我什么时候应该 mock ?

java - 为什么递归中值没有改变?

java - 使用jna监听鼠标事件时如何区分向上滚动还是向下滚动

java - 使用正则表达式将字符串拆分为 3 部分

.net - 在 HTML Helpers 中使用 CaSTLe Windsor 进行依赖注入(inject)

c# - 声明具体实现具有具体类型的接口(interface)

php - 单例结构