开发者

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

开发者 https://www.devze.com 2023-03-25 14:31 出处:网络
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 class开发者_StackOverflowes:

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 class开发者_StackOverflowes:

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


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.


Add

 context.assertIsSatisfied();

to the end of your test. This will have JMock confirm all the expectations you defined were met.

0

精彩评论

暂无评论...
验证码 换一张
取 消