如何捕获测试中创建的模拟类型的实例?

时间:2014-04-23 16:39:33

标签: java jmockit

我正在尝试捕获在测试中创建的模拟类型的实例。我无法让它发挥作用。

鉴于课程:

public class Foo {}

以下测试失败:

@RunWith(JMockit.class)
public class FooTest {

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

}

知道我可能做错了吗?

我也尝试使用字段而不是测试参数(见下文),它也失败了:

@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)));
    }

}

documentation表示它应该有效,但我无法让它发挥作用。

由于

JMockit v1.7

2 个答案:

答案 0 :(得分:1)

最简单的方法如下:

@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))));
    }};
}

但是,上面使用的withCapture(T)方法仅添加到尚未发布的JMockit 1.8中。

答案 1 :(得分:0)

Inspired by an answer to another question on this site,我让它与之合作:

@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])));
    }

}

呸。