为什么jmockit期望块抛出illegalmonitorstateexception?

qlckcl4x  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(639)

我使用jmockit来模拟junit测试的某个示例。但我发现它不是execute,因为jmockit expcatations块总是抛出illegalmonitorstateexception。
例如,源代码是:

public class ForTest {
    public static class A {
        public String getStr() {
            return "a";
        }
    }

    public String getStrFrom(A a) {
        return a.getStr();
    }
}

junit测试代码是:

public class ForTestTest {
    @Tested
    ForTest forTest;

    @Injectable
    ForTest.A a;

    @Test
    public void test_str() {
        new Expectations() {{
            a.getStr();
            result = "b";
        }};

        Assertions.assertEquals("b", forTest.getStrFrom(a));

        new Verifications() {{
            a.getStr();
            times = 1;
        }};
    }
}

当我运行测试时,出现了一个异常:

java.lang.IllegalMonitorStateException
at com.huawei.genexcloud.nsp.worker.ForTestTest$1.<init>(ForTestTest.java:30)
at com.huawei.genexcloud.nsp.worker.ForTestTest.test_str(ForTestTest.java:27)
Suppressed: Missing 1 invocation to:
com.huawei.genexcloud.nsp.worker.ForTest$A#getStr()
on mock instance: com.huawei.genexcloud.nsp.worker.ForTest$A@589b3632
Caused by: Missing invocations
at com.huawei.genexcloud.nsp.worker.ForTest$A.getStr(ForTest.java)
at com.huawei.genexcloud.nsp.worker.ForTestTest$1.<init>(ForTestTest.java:28)
at com.huawei.genexcloud.nsp.worker.ForTestTest.test_str(ForTestTest.java:27)

我的ide是intellij idea 2020.2.3。我的jdk是openjdk1.8,jmockit的版本是1.49。我想这是我的ide设置有问题,但我不知道如何修复它。
我试着和格雷德一起做测试。效果很好。

qaxu7uf2

qaxu7uf21#

在eclipse中运行时,这对我很有用。我看不出语法有什么明显的错误。
如果它在命令行工作,但在ide中不工作,那么ide中很可能存在配置问题。请记住,您必须配置javaagent才能让jmockit工作—这可能是ide中的额外步骤。
另一个可能对你有帮助的技巧是,你可以把“验证”合并成“期望”。编写代码要少一点。

@Test
public void test_str() {
    new Expectations() {{
        // provides an expected value *AND* ensures called once-and-only-once
        a.getStr();
        times = 1;
        result = "b";
    }};

    Assertions.assertEquals("b", forTest.getStrFrom(a));
}

相关问题