JMockit:在 MockUp 中使用 Invocation 调用原始逻辑


#Java Jmockit


测试示例

被测试类:

package demo;

public class Calculator {

    // 非静态函数
    public int add(int a, int b) {
        return a+b;
    }

    // 静态函数
    public static int staticAdd(int a, int b) {
        return a+b;
    }

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

}

测试1:

package demo;

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

public class CalculatorTest {

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

        // mock
        new MockUp<Calculator>() {
            @Mock
            public int add(Invocation invocation, int a, int b) {
                // 当 a == 1 时,调用原始逻辑
                if (a == 1) {
                    return invocation.proceed(a, b);
                }
                return 1;
            }
        };

        System.out.println(calculator.add(1, 2));
        System.out.println(calculator.add(2, 1));
    }

}

执行结果:

3
1

测试2:

package demo;

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

public class CalculatorTest {

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

        // mock
        new MockUp<Calculator>() {
            @Mock
            public int add(Invocation invocation, int a, int b) {
                // 当 a == 1 时,调用原始逻辑
                if (a == 1) {
                    return invocation.proceed(a, b);
                }
                return 1;
            }
            @Mock
            public void noop(Invocation invocation) {
                System.out.println("调用原始逻辑");
                invocation.proceed();
            }
        };

        calculator.noop();
    }

}

执行结果:

调用原始逻辑
没有被 mock


( 本文完 )