Question

I am trying to capture an instance of a mocked type that is created within the test. I cannot get it to work.

Given the class:

public class Foo {}

The following test fails:

@RunWith(JMockit.class)
public class FooTest {

    @Test
    public void capturing(@Capturing Foo expected) {
        final Foo actual = new Foo();
        assertThat(actual, is(theInstance(expected)));
    }

}

Any idea what I could be doing wrong?

I also tried using a field instead of a test argument (see below) and it fails too:

@RunWith(JMockit.class)
public class FooTest {

    // The captured instance is now a field, instead of a test parameter.
    @Capturing private Foo expected;

    @Test
    public void capturing() {
        final Foo actual = new Foo();
        assertThat(actual, is(theInstance(expected)));
    }

}

The documentation states that it should work, but I am not able to get it work.

Thanks

JMockit v1.7

Was it helpful?

Solution 2

Inspired by an answer to another question on this site, I got it to work with:

@RunWith(JMockit.class)
public class FooTest {

    @Test
    public void capturing(@Mocked final Foo unused) {
        final Foo expected[] = new Foo[1];
        new Expectations() {{
            new Foo();
            result = new Delegate() {
                void captureIt(Invocation inv) {
                    expected[0] = (Foo) inv.getInvokedInstance();
                }
            };
        }};

        final Foo actual = new Foo();
        assertThat(actual, is(theInstance(expected[0])));
    }

}

Yuck.

OTHER TIPS

The easiest way is as follows:

@Test
public void capturing(@Mocked Foo unused)
{
    final Foo actual = new Foo();

    new Verifications() {{
        List<Foo> expected = withCapture(new Foo());
        assertThat(actual, is(theInstance(expected.get(0))));
    }};
}

However, the withCapture(T) method used above was only added in JMockit 1.8, which has not been released yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top