从子类中模拟方法,同时单元测试类方法

时间:2013-05-22 05:47:32

标签: java unit-testing junit mockito

我正在尝试为类的特定方法编写单元测试 - foo。这个类扩展了另一个类 - bar,它位于一个外部jar中 问题是这个基础bar有一些与数据库交互的方法,我不想实际调用它。

我尝试创建这个基类foo的模拟,但这不起作用。它实际上试图连接到数据库而不是模拟。

@Test
public void testSomeMethod(){
bar b= mock(bar.class);
when(b.calldatabase()).thenReturn(resultset); //calldatabse is in base class bar

//create expected object, and set properties here
Results expected = new Results();
expectedResult = foo.MethodUnderTest(); // this has call to calldatabase and then uses resultset mocked above
assert()...
}

我正在使用JUnit4和Mockito。
它是否真的可以像这样 - 在基类中模拟方法但实际上测试派生类?如果没有,我该如何测试呢? 如果需要,我可以更改基类,并根据需要使用任何其他工具/库。

1 个答案:

答案 0 :(得分:7)

你嘲笑了Bar的一个实例,但是这个模拟的Bar从未用在你的测试中,因为你测试了一个单独的实例:foo。创建模拟Bar实例会创建一个新的动态生成的类的对象,该类会覆盖Bar类的所有方法。它不会更改Bar类中方法的内部字节代码。

你需要的是间谍或部分模拟:

Foo partiallyMockedFoo = spy(new Foo());

// stub the doSomethingWithTheDatabase()
when(partiallyMockedFoo.doSomethingWithTheDatabase()).thenReturn("1234"); 

// call the real method, that internally calls doSomethingWithTheDatabase()
partiallyMockedFoo.methodUnderTest();