JMockit:使用 MockUp mock 私有函数


#Java Jmockit


该特性在以后的版本可能被废弃。详见 1.45 版本的变更日志:

Added a warning (printed to standard output) for @Mock methods that target a private method or constructor. The intent is to disallow such mock methods in a future version.

测试示例

被测试类

package demo;

public class Calculator {

    // 空函数
    public void noop() {
        System.out.println("没有被 mock");
        privateMethod();
    }

    private void privateMethod() {
        System.out.println("private 函数");
    }

}

测试

package demo;

import mockit.Mock;
import mockit.MockUp;
import org.junit.Test;

public class CalculatorTest {

    @Test
    public void test_add_01() {
        Calculator calculator = new Calculator();

        System.out.println("--- mock 之前 ---");
        calculator.noop();

        // mock
        new MockUp<Calculator>() {
            @Mock
            private void privateMethod() {
                System.out.println("私有函数被mock了");
            }
        };

        System.out.println("--- mock 之后 ---");
        calculator.noop();
    }

}

执行结果:

--- mock 之前 ---
没有被 mock
private 函数
WARNING: fake for private method Calculator#privateMethod()V found; such fakes will no longer be supported
--- mock 之后 ---
没有被 mock
私有函数被mock了



( 本文完 )