gpt4 book ai didi

Java Mock 对象,没有依赖注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:53:10 29 4
gpt4 key购买 nike

我对 JUnit 测试套件中的模拟对象很感兴趣,但是我只遇到过使用依赖注入(inject)来注入(inject)模拟对象的模拟框架。但是,我希望能够模拟类/函数而不必注入(inject)该模拟对象,就像 python 中的 @patch() 一样。

简单的例子:

//dependency injection
public String bar(Foo foo) {
return foo.foo(); //just pass in mock Foo object
}
//.... onto test code
Foo mockedFoo = <Mocked Foo object>;
String response = bar(mockedFoo);
assertEqual(response, <mockedFoo return value>);


//case I am looking for
public String bar() {
Foo foo = new Foo(); //how to create mock object here?
return foo.foo(); //or simply how to mock a single function?
}
//... onto test code
<force the Foo class or foo method to be mocked from here without touching bar() source code>
String response = bar();
assertEqual(response, <mocked response>);

最佳答案

您可以使用 Powermock 检测被测类,以便在调用 new 时返回模拟。

Powermock mock constructor tutorial

你的代码看起来像这样:

RunWith(PowerMockRunner.class)
@PrepareForTest( Bar.class )
public class BarTest {


@Test
public void test(){
Foo mockedFoo = createMock(Foo.class);
//set up mockedFoo here
...

//This will make a call to new Foo() inside Bar.class
//return your mock instead of a real new one
expectNew(Foo.class).andReturn(mockedFoo);

...
replay(mockedFoo, File.class);

Bar bar = new Bar();
String response = bar.bar();

assertEqual(response, <mocked response>);

verify(mockedFoo, File.class);


}

}

关于Java Mock 对象,没有依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27558284/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com