1 回答

TA貢獻1788條經(jīng)驗 獲得超4個贊
一種選擇是將您自己的(模擬的)實現(xiàn)替換SomeOtherClassProcessor為MyClass使用反射:
MyClass myClass = new MyClass();
SomeOtherProcessor01 mockProcessor01 = mock(SomeOtherProcessor01.class);
// reflection bit: find the field by its name
// handle NoSuchFieldException
Field someProcessorField = MyClass.getDeclaredField("someOtherProcessor01");
// the field is declared as private, so make it accessible in order to work with it
someProcessorField.setAccessible(true);
// now set your mocked processor into the field.
// First argument is the object to change; second argument - new value for the field
someProcessorField.set(myClass, mockProcessor01);
附言。使用 PowerMock 和/或反射是向糟糕的設(shè)計投降(根據(jù) Timothy :)。您不應該依賴尚未經(jīng)過充分測試的代碼,如果是,您不應該再次嘗試對其進行測試。假設(shè)您的測試實際上揭示了一個錯誤——如果您不控制代碼,您將如何修復它?假設(shè) Java 11 變成了一個東西,禁止你使用反射。假設(shè)您正在測試的代碼發(fā)生變化并且字段被重命名 - 通過反射,您沒有編譯時安全......潛在問題列表繼續(xù)
添加回答
舉報