对JMockit上所有实例的期望

时间:2019-09-18 22:41:31

标签: jmockit

我期望JMockit对所有实例设置期望。但是,当我向混合中添加构造函数期望时,该方法不起作用。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,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();
    }