简体   繁体   中英

How to mock the view in the MVC integration testing using JUnit and EasyMock

I would like to mock a view implementation of the MVC design pattern . I have implemented the MVP (another MVC variation), and would like to test if the certain methods in the view get called correctly by the controller when a state change happens on the model. The following shows the sequence of method calls on the model , controller and view .

Model:

model.setProperty("newProperty");

Controller:

@Override
    public void propertyChange(PropertyChangeEvent evt) {
        for (View view : views) {
            view.modelPropertyChange(evt);
        }
    }

View: This result to the view being called as like:

@Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if ("Property".equals(evt.getPropertyName())) {
            updateView();
        }
    }

Question: How do verify(using EasyMock in the JUnit test), the expected order of method(with valid argument(s)) execution? I expect view.modelPropertyChange(evt) to get called and the expect view.isViewUpdated() to return true on the view object. How do I say that in my JUnit test? Please help!

@RunWith(JUnit4.class)
public class ControllerTest {
  @Test
  public void updateView() {
    PropertyChangeEvent evt = new PropertyChangeEvent( ... );
    View mockView = EasyMock.createMock(View.class);
    mockView.modelPropertyChange(evt);
    EasyMock.replay(mockView);

    Controller controller = new Controller( ... );
    controller.propertyChange(mockView);
    EasyMock.verify(mockView);
  }
}

Note that the Controller.propertyChange() doesn't call View.isViewUpdated() so there is no need to mock isViewUpdated . You would test isViewUpdated in a test for the View class.

If propertyChange did call isViewUpdated then you would add the following call before EasyMock.replay() :

EasyMock.expect(mockView.isViewUpdated()).andReturn(true);

Note that EasyMock.createMock() does not enforce that the mocked methods be called in the order they were mocked. If you want the method order to be enforced, use EasyMock.createStrictMock()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM