Java Mock对象,没有依赖注入

时间:2014-12-19 00:54:47

标签: java unit-testing junit dependency-injection mocking

我对在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>);

2 个答案:

答案 0 :(得分:3)

您可以使用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);


}

}

答案 1 :(得分:1)

简单地说,你可以像这样嘲笑Foo

public String bar() {
    Foo foo = Mockito.mock(Foo.class);
    return foo.foo();
}

但问题是foo.foo()基本上什么都不做,因为你还没有定义当我们调用模拟版本时#foo()应返回的内容。使用更完整的示例,您可以执行以下操作:

class MyTest {

    Foo mockedFoo = Mockito.mock(Foo.class);

    @Before
    public void setUp() throws Exception {
        Mockito.when(mockedFoo.foo()).thenReturn("This is mocked!");
    }

    @Test
    public void testMock() {
        String returnedFoo = mockedFoo.foo();
        Assert.assertEquals("This is mocked!", returnedFoo);
    }
}