1 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
一種選擇是將您自己的(模擬的)實(shí)現(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ì)投降(根據(jù) Timothy :)。您不應(yīng)該依賴尚未經(jīng)過充分測試的代碼,如果是,您不應(yīng)該再次嘗試對(duì)其進(jìn)行測試。假設(shè)您的測試實(shí)際上揭示了一個(gè)錯(cuò)誤——如果您不控制代碼,您將如何修復(fù)它?假設(shè) Java 11 變成了一個(gè)東西,禁止你使用反射。假設(shè)您正在測試的代碼發(fā)生變化并且字段被重命名 - 通過反射,您沒有編譯時(shí)安全......潛在問題列表繼續(xù)
添加回答
舉報(bào)