Java模拟 - 用mock对象动态替换类

时间:2018-04-13 16:59:40

标签: java unit-testing mocking

我希望在运行时用模拟替换类的所有实例。这可能吗?例如,在测试中,我想将class Bar标记为模拟类。在测试范围内,在class Foo的构造函数中,new Bar()应该返回一个模拟的Bar实例,而不是真正的类。

class Bar {
    public int GiveMe5() {
        return 5;
    }
}

public class Foo {
    private Bar bar;

    Foo() {
        bar = new Bar();
    }
}

然后在我的测试中:

class TestFoo {
    @Before
    public void setUp() {
        // Tell the mocking framework every instance of Bar should be replaced with a mocked instance
    }
    @Test
    private void testFoo() {
        Foo foo = new Foo(); // Foo.bar should reference a mocked instance of Bar()
    }
}

3 个答案:

答案 0 :(得分:2)

尝试PowerMockito和whenNew方法。您应该能够在调用Foo类的构造函数时返回模拟实例。

答案 1 :(得分:1)

你可以在Mockito中使用模拟新实例来做复杂的事情,但是只需要在测试中注入你需要的依赖项就更简单了。

public class Foo {

    private Bar bar;

    Foo(Bar bar) {
        this.bar = bar;
    }
}

此时,您可以将所需的Bar实例注入此类,包括模拟。

答案 2 :(得分:0)

你可以使用一个模拟库来支持模拟" newed" (未来)对象。 JMockit和PowerMock都支持它。例如,使用JMockit,测试看起来像:

public class FooTest {
    @Test
    public void mockAllInstancesOfAClass(@Mocked Bar anyBar) {
        new Expectations() {{ anyBar.giveMe5(); result = 123; }};

        Foo foo = new Foo();
        // call method in foo which uses Bar objects

        // asserts and/or verifications
    }
}