Java Mock 对象,无需依赖注入
2022-09-04 22:54:51
我对JUnit测试套件中的模拟对象感兴趣,但是我只遇到过使用依赖注入来注入模拟对象的模拟框架。但是,我希望能够模拟类/函数,而不必注入该模拟对象,就像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>);