0

I am using JMockIt 1.8, and I have the following classes:

public class SimpleUser {
    public static void useSimple(final SimpleClass simple) {
        System.out.println("useSimple called");
    }

    public void createAndUse() {
        final SimpleClass simple = new SimpleClass();
        simple.method();
        SimpleUser.useSimple(simple);
    }
}

and

public class SimpleClass {
    public void method() {
    }
}

With the following test class:

public class Tester {
    @Mocked SimpleClass simple;

    @Test
    public void test() {
        new Expectations(SimpleUser.class) {
            {
                new SimpleClass();

                simple.method();

                SimpleUser.useSimple(simple);
            }
        };

        SimpleUser user = new SimpleUser();
        user.createAndUse();
    }
}

And this test passes.

However, when I remove the call to simple.method() in SimpleUser and the expectation for simple.method() in Tester, the test errors with:

mockit.internal.MissingInvocation: Missing invocation of
  SimpleUser#useSimple(SimpleClass simple)
    with arguments: SimpleClass@45490852

I can cause this modified version of the test to pass by changing the expectation from SimpleUser.useSimple(simple) to SimpleUser.useSimple((SimpleClass) any), but I would like to assert that the instance being passed through is correct.


Why does the behavior change depending on whether method() is called and how can I ensure that SimpleUser.useSimple() is called with the SimpleClass created in createAndUse(), without resorting to calling a method within SimpleClass.

Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
  • 1
    is there a typo in your expectation - is `SimpleUser.useVisitor(simple);` correct? – vikingsteve Feb 05 '15 at 12:26
  • Thanks, that was a typo I made when reducing my code down to a MCV example – Andrew Stubbs Feb 05 '15 at 12:29
  • Is it really necessary to verify that a new `SimpleClass` instance was created? Seems to me like an over-specified test. I would simply verify the method was called with a non-null argument: `SimpleUser.useSimple((SimpleClass) withNotNull())`. – Rogério Feb 05 '15 at 20:51

1 Answers1

1

I can't explain

why does the behavior change depending on whether method() is called

but with JMockit 1.14 the behavior is always the same : the test fails simple.method() is called or not.

However, you can test what you want by adding a line in the expectation block (tested with JMockit 1.14) :

public class Tester {
    @Mocked
    SimpleClass simple;

    @Test
    public void test() {
        new Expectations(SimpleUser.class) {
            {
                new SimpleClass();
                result = simple;   // <- here

                simple.method();

                SimpleUser.useSimple(simple);
            }
        };

        SimpleUser user = new SimpleUser();
        user.createAndUse();
    }
}

Hope this help ...

emgr
  • 53
  • 1
  • 5