[英]JMockit mock private method in @PostConstruct
在我的測試類中,有一個@PostConstruct
注釋方法,該方法調用另一個私有方法。
@PostConstruct
public void init() {
longWork(); // private method
}
JMockit的默認行為是在注入時執行@Tested
類的@PostConstruct
方法。
如果@Tested類的方法帶有javax.annotations.PostConstruct注釋,則應在注入后立即執行。
https://github.com/jmockit/jmockit1/issues/13
JMockit調用了我不想要的init()
方法。
從線程轉儲:
at com.me.Worker.longWork(Worker.java:56)
at com.me.Worker.longWork.init(Worker.java:47)
...
at mockit.internal.util.MethodReflection.invoke(MethodReflection.java:96)
該呼叫如何被模擬/刪除/阻止?
我試圖模擬init
和longWork
方法,如下所示。 但是,由於尚未注入sut
,因此會導致NullPointerException
。
@Before
public void recordExpectationsForPostConstruct()
{
new NonStrictExpectations(sut) {{ invoke(sut, "init"); }};
}
您可以嘗試手動初始化要測試的類,而無需使用@Tested。 然后,通過setter方法(或使用mockit.Deencapsulation.setField()方法)設置模擬依賴項。
您可以嘗試類似的操作;
//Define your class under test without any annotation
private MyServiceImpl serviceToBeTested;
//Create mock dependencies here using @Mocked like below
@Mocked Dependency mockInstance;
@Before
public void setup() {
//Initialize your class under test here (or you can do it while declaring it also).
serviceToBeTested = new MyServiceImpl();
//Set dependencies via setter (or using mockit.Deencapsulation.setField() method)
serviceToBeTested.setMyDependency(mockInstance);
//Optionally add your expectations on mock instances which are common for all tests
new Expectations() {{
mockInstance.getName(); result = "Test Name";
...
}};
}
@Test
public void testMyMethod(@Mocked AnotherDependency anotherMock) {
//Add your expectations on mock instances specifics to this test method.
new Expectations() {{
mockInstance.getStatus(); result = "OK";
anotherMock.longWork(); result = true;
...
}};
//Set dependencies via setter or using mockit.Deencapsulation.setField() method
Deencapsulation.setField(serviceToBeTested, "myAnotherDep", anotherMock);
//Invoke the desired method to be tested
serviceToBeTested.myMethod();
//Do the verifications & assertions
new Verifications() {{
....
....
}};
}
也許您可以將longWork方法委托給另一個類並模擬該類。 編寫測試時遇到困難通常是設計缺陷的標志
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.