简体   繁体   English

JMockit:验证测试的 class 实例的方法调用

[英]JMockit: Verify method call of tested class instance

I currently have the following code for testing:我目前有以下代码进行测试:

public class TestClass {
    @Tested
    private MyClass myClass = new MyClass();

    @Test
    public void test(@Mocked IntWrapper wrapper) {
        new Expectations() {{
            wrapper.value();
            result = 20;
        }};

        myClass.doSomething(wrapper);

        new Verifications() {{
            myClass.larger();
            times = 1;
        }};
    }
}

class IntWrapper {
    public int value() {
        return 0;
    }
}

class MyClass {
    public void doSomething(IntWrapper wrapper) {
        if (wrapper.value() <= 10) {
            smaller();
        } else {
            larger();
        }

    }

    public void larger() {
        System.out.println("Larger than 10");
    }

    public void smaller() {
        System.out.println("Smaller than 10");
    }
}

The test code above will throw an java.lang.NullPointerException in the verification part.上面的测试代码会在验证部分抛出 java.lang.NullPointerException。 Is there something that I am not understanding with regards to the use of the Tested classes?关于 Tested 类的使用,我有什么不明白的地方吗? Or are there any ways I can verify method call of unmocked class instances?或者有什么方法可以验证未模拟的 class 实例的方法调用?

Thank you!谢谢!

JMockit can be finicky. JMockit 可能很挑剔。 I tend to我倾向于

  • consolidate Verifications into Expectations - just cleaner将验证整合到期望中 - 更简洁
  • add the class-under-test to the expectations initializer (forcing it to be mocked)将被测类添加到期望初始化程序(强制它被模拟)
  • avoid specifying a constructor with @Tested, use @Injectable as necessary, unless you need a specific ctor.避免使用@Tested 指定构造函数,必要时使用@Injectable,除非您需要特定的ctor。
public class TestClass {
    @Tested
    private MyClass myClass;

    @Test
    public void test(@Mocked IntWrapper wrapper) {
        new Expectations(myClass) {{
            wrapper.value();
            times=1;
            result = 20;

            myClass.larger();
            times=1;
        }};

        myClass.doSomething(wrapper);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM