我正在尝试为类的特定方法 - 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 一起使用。
真的有可能这样吗——模拟基类中的方法但实际测试派生类?如果没有,我该如何测试?
如果需要,我可以更改基类,并根据需要使用任何其他工具/库。
最佳答案
您模拟了 Bar 的实例,但这个模拟的 Bar 从未在您的测试中使用,因为您测试了一个单独的实例:foo。创建模拟 Bar 实例会创建一个动态生成的新类的对象,该类会重写 Bar 类的所有方法。它不会更改 Bar 类中方法的内部字节码。
你需要的是一个 Spy,或者一个部分模拟:
Foo partiallyMockedFoo = spy(new Foo());
// stub the doSomethingWithTheDatabase()
when(partiallyMockedFoo.doSomethingWithTheDatabase()).thenReturn("1234");
// call the real method, that internally calls doSomethingWithTheDatabase()
partiallyMockedFoo.methodUnderTest();
关于java - 在对类方法进行单元测试时模拟子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16684320/