[英]Mocking methods from subclass while unit testing class methods
我正在嘗試為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()...
}
我在Mockito中使用JUnit4。
真的有可能這樣嗎?在基類中模擬方法但實際上在測試派生類嗎? 如果沒有,我該如何測試?
如果需要,我可以更改基類,並根據需要使用任何其他工具/庫。
您模擬了Bar的實例,但是由於您測試了單獨的實例foo,因此該模擬的Bar從未在測試中使用。 創建模擬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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.