views:

28

answers:

1

Hi,

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!

+1  A: 
@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()

NamshubWriter
I get an error when I run EasyMock.verify(mockView):"Expectation failure on verify..."
walters
Usually you can tell from the stack trace what the problem is. The above code tells EasyMock to expect that "modelPropertyChange" will be called on the View with an event that is equal to "evt". If you get an exception in EasyMock.verify() that usually indicates that the method wasn't called.
NamshubWriter