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
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.