对 JMockit 上所有实例的期望

expectations on all instances on JMockit

我期待 JMockit 对 all 个实例设置期望。但是,当我将构造函数期望添加到组合中时,这不起作用。

class Foo {
    Foo(int i) {}
    void foo() {}
}

@Test
public void expectationsOnAllInstances__Works(@Mocked Foo foo) {
    new Expectations() {{
        foo.foo();
    }};
    new Foo(3).foo();
}

@Test
public void expectationsOnAllInstances__DoesntWork(@Mocked Foo foo) {
    new Expectations() {{
        new Foo(3);  // <==== this constructor expectation messes things up ...
        foo.foo();
    }};
    new Foo(3).foo();
}

第二次测试失败并出现错误:

Missing 1 invocation to:
Foo#foo()
   on mock instance: Foo@617faa95
instead got:
Foo#foo()
   on mock instance: Foo@1e127982

JMockit 1.48

谢谢!

好吧,expectationsOnAllInstances__DoesntWork 测试与记录和回放的预期不一致...

您真正想要的是这两个其他版本之一:

    @Test
    public void expectationsOnAllInstances_consistent1(@Mocked Foo foo) {
        new Expectations() {{
            new Foo(3).foo();
        }};

        new Foo(3).foo();
    }

    @Test
    public void expectationsOnAllInstances_consistent2(@Mocked Foo foo) {
        new Expectations() {{
            new Foo(3);
            foo.foo();
        }};

        new Foo(3);
        foo.foo();
    }