Search code examples
jmockhamcrest

JMock expectations - is it possible to check the actual value in the expectation?


I'm new to Java and JMock and I'm currently trying to get my head around mocking. I've created this dummy test with dummy classes:

public class JmockUnitTest {
    private Mockery context = new Mockery();

    private Class2 class2 = context.mock(Class2.class);

    @Test
    public void testMethod() {

        Class1 class1 = new Class1();

        context.checking(new Expectations() {{
            oneOf(class2).method2();
            will(returnValue(1234));
        }});

        class1.method1();
    }


public class Class1 {

    public void method1() {
        Class2 class2 = new Class2Impl();
        Integer time = class2.method2();
    }
}

public interface Class2 {
    public Integer method2();
}

public class Class2Impl implements Class2 {
    public Integer method2() {
        return 10;
    }
}

}

My Class2Impl.method2() return the integer 10 but the expectation is set to 1234. The test still passes so I just wanted to clarify does this example jus expect the return type to be any Integer? Is it possible or does it even make sense to check that it returns 10?

Thanks


Solution

  • The problem is that you're not passing the instance of Class2 into the instance of Class1, there's no way to bind the two objects together. JMock is designed for testing how objects collaborate, so there has to be a way to set up the graph of objects. That might be a setter or through the constructor. In your case, if Class2 really is so simple that it just returns a value, then it might not be worth using a mock but using a real instance.

    If you do use a mock, then as the other post says, you need to use @RunWith(JMock.class), or assertIsSatisfied(), or try the new mockery junit rule that's in the version control.