Search code examples
javaunit-testingdesign-patternsmockitopresenter-first

Write Mockito Test for Presenter Class (Presenter First Pattern)


I'm trying to get familiar with TDD and the Presenter First Pattern. Right now I'm stuck writing a test case for my Presenter.class. My goal is to cover the whole Presenter.class including the Action Event but I have no glue how to do it with 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() {
    }
}

Thanks in advance!


Solution

  • At first... thank you guys!

    After a while i figured out this solution and stuck to it because I don't wanted to implement any interfaces at the presenter class neither I wanted to create stub classes in my tests.

    IView

    public interface IView {
        public void setText(String text);
    }
    

    IModel

    public interface IModel {
        public String getText();
        public void addModelChangeListener(Action a);
    }
    

    Presenter

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