我用我想測試的方法創建了一個bean。不幸的是,它是一個帶有PostConstruct註釋的bean。我不想調用PostConstruct方法。 我該怎麼做?Jmockit和@PostConstruct bean
我試過2種不同的方法(如下面的例子所示),但沒有工作; init()仍然被調用。
有人能給我一個詳細的例子,說明如何做到這一點?
DirBean.java
@Singleton
@Startup
public class DirBean implements TimedObject {
@Resource
protected TimerService timer;
@PostConstruct
public void init() {
// some code I don't want to run
}
public void methodIwantToTest() {
// test this code
}
}
MyBeanTest.java
public class MyBeanTest {
@Tested
DirBean tested;
@Before
public void recordExpectationsForPostConstruct() {
new Expectations(tested) {
{
invoke(tested, "init");
}
};
}
@Test
public void testMyDirBeanCall() {
new MockUp<DirBean>() {
@Mock
void init() {
}
};
tested.methodIwantToTest();
}
}
MyBeanTest2.java(工程)
public class MyBeanTest2 {
@Tested
DirBean tested;
@Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
@Mock
void init() {}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}
MyBeanTest3.java(工程)
public class MyBeanTest3 {
DirBean dirBean = null;
@Mock
SubBean1 mockSubBean1;
@Before
public void setupDependenciesManually() {
dirBean = new DirBean();
dirBean.subBean1 = mockSubBean1;
}
@Test
public void testMyDirBeanCall() {
dirBean.methodIwantToTest();
}
}
MyBeanTest4.java(帶NullPointerException異常失敗上的invoke())
public class MyBeanTest4 {
@Tested
DirBean tested;
@Before
public void recordExpectationsForCallsInsideInit() {
new Expectations(tested) {
{
Deencapsulation.invoke(tested, "methodCalledfromInit", anyInt);
}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}
我想你會了解它的錯誤的方式。 init()方法是被測試類的重要組成部分,它不應該被嘲笑。相反,如果需要,可以模擬其調用的任何其他組件。 –
可能,但問題是在測試之前調用init()。所以如果我試圖模擬init()內部的私人調用,它會給我一個被測試變量的空指針異常。也許我不能在這種情況下使用@Tested? – Miyagi
如果'init()'在同一個測試類('private'或不)上調用其他方法,它們也不應該被嘲笑。 「應該」被嘲笑的唯一方法是屬於除被測試者之外的其他*類別的方法。如果我知道[實際問題是什麼],它會更容易幫助(http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –