Вопрос

Is there the best way to make nice mock by using JMock?

For example:

public interface Dependency {
    void someSetUp();
    void interactionUnderTest();
    void someCleaningAfterWork();
}

public class CUT {
    private Dependency dependency;

    public void methodUnderTest() {
        dependency.someSetUp();
        dependency.interactionUnderTest();
        dependency.someCleaningAfterWork();
    }

    public void setDepencency(Dependency dependency) {
        this.dependency = dependency;
    }
}

For Mockito the solution is simple:

@Test
public void mockitoExample() throws Exception {
    Dependency dependency = mock(Dependency.class);
    classUnderTest.setDepencency(dependency);
    classUnderTest.methodUnderTest();
    verify(dependency).interactionUnderTest();
}

But for JMock I've found only this solution:

@Test
public void jMockExample() throws Exception {
    JUnit4Mockery ctx = new JUnit4Mockery();
    final Dependency dependency = ctx.mock(Dependency.class);
    classUnderTest.setDepencency(dependency);
    ctx.checking(new Expectations() {{
        allowing(dependency).someSetUp();
        one(dependency).interactionUnderTest();
        allowing(dependency).someCleaningAfterWork();
    }});

    classUnderTest.methodUnderTest();
}

The problem is in these lines:

allowing(dependency).someSetUp();
and
allowing(dependency).someCleaningAfterWork();

If methodUnderTest changes, for example by calling another method from Dependency, I'll have to manually modify the test in case of using JMock. Is there the way to avoid it?

P.S. Sorry about my English

Это было полезно?

Решение

If you really want to, you can use allowing(dependency) which will allow everything on the object.

There is a reason that we don't support "nice" mocks, which is that we don't want stuff happening arbitrarily in our code without driving it from the unit test. On the whole, we find that this sort of brittleness comes from weakness in our design, and we use the test feedback to help us discover that.

In this example, I would be interested in the relationship, the "protocol" between the different dependency methods. I would want to isolate that so that it's implemented once, which means I would only need to test it in once place, so a "nice" mock would not be as useful.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top