我有一個單元測試失敗,因爲它間接調用了一個依賴於服務的方法。但是,當單元測試運行時,服務處於脫機狀態。我試圖用Mockito來嘲笑這個服務依賴方法的行爲,但問題是這個方法是最終類中的靜態方法,所以在這種情況下Mockito不起作用。單元測試失敗,因爲服務處於脫機狀態
我也嘗試過使用PowerMock與Mockito,但由於該方法不是直接從單元測試中調用,所以不起作用。這是我的單元測試的骨架:
@RunWith(PowerMockRunner.class)
@PrepareForTest(FinalClassWithStaticMethod.class)
public class MyObjTestCase {
@Test public void myRandomTest() throws Exception {
PowerMockito.mockStatic(FinalClassWithStaticMethod.class);
MyObj returnObj = new MyObj();
// setup fields for returnObj
...
...
PowerMockito.when(FinalClassWithStaticMethod.staticMethod((AnotherObj)anyObject())).thenReturn(returnObj);
AnotherObj obj = new AnotherObj();
// setup fields for obj...
MyObj mockedObj = FinalClassWithStaticMethod.staticMethod(obj); // This returns the mocked value.
// TestUtil.staticMethod calls another class' method which calls FinalClassWithStaticMethod.staticMethod.
MyObj myObj = TestUtil.staticMethod(obj); // This does not return mocked value.
}
}
我的問題:
甚至意味着這些場景的單元測試?
有沒有辦法讓我的單元測試在沒有修改最終課程的情況下工作?如果我不得不修改現有類,那麼對相關代碼的影響最小的正確方法是什麼?雖然這是一個特定的場景,但是鏈接到展示這種重構的例子將會很有幫助。