繁体   English   中英

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

[英]Java mocks - dynamically replace class with mock object

我希望在运行时将类的所有实例替换为模拟。 这可能吗? 例如,在一个测试中,我想将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()
    }
}

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

您可以通过在Mockito中模拟新实例来做复杂的事情,但是简单地注入需要测试的依赖关系要简单得多。

public class Foo {

    private Bar bar;

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

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

您可以使用支持“新”(未来)对象模拟的模拟库来实现。 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
    }
}

暂无
暂无

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

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