2.1 创建并使用mock对象

JMockit可以mock任意class、interface。可以将mock对象声明为域或者方法的参数。默认情况下,mock对象的所有 非private 的方法(包括除了object的其他继承方法)都会被mock,对这些方法的调用不会执行原有代码,而是会转交给JMockit处理。进行mock风格的测试需要三个步骤:expectation--> 方法调用 --> verication,示例如下:

@Mocked Dependency mockedDependency

@Test
public void test(final @Mocked AnotherDenpendency anotherDependency) {
    new Expectations() {{
        mockedDependency.mockedMethod();
        result = 1;
    }};

    codeUnderTest();

    new Verifications(){{
        anotherDependency.anotherMethod();
        times = 1;
    }};
}

JMockit会对@Mocked注解的对象进行依赖注入,所以在Expectation、Verication以及CodeUnderTest中可以直接使用mock对象,不需要手动实例化。

在CodeUnderTest中通过new创建了一个Dependency并调用了其方法,JMockit会自动将这个方法调用转移到mock对象上。

public class CodeUnderTest {
    public int testMethod() {
        Dependency dependency = new Dependency();
        return dependency.mockMethod();
    }
}
public class Dependency {
    public int mockMethod() {
        return 1;
    }
}

Dependency类的mockMethod方法原本返回值为1,在Expectation中将其返回值设置为2,则在测试过程中该方法将会返回2。

@Mocked
Dependency dependency;

@Test
public void TestMethod() throws Exception {
    new NonStrictExpectations() {{
        dependency.mockMethod();
        result = 2;
    }};

    CodeUnderTest codeUnderTest = new CodeUnderTest();
    assertEquals(2, codeUnderTest.testMethod());
}

你可能感兴趣的:(2.1 创建并使用mock对象)