我已经创建了一个带有我想要测试的方法的bean。不幸的是,它是一个带有PostConstruct注释的bean。我不想调用PostConstruct方法。我该怎么做呢?
我尝试了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 (FAILS with NullPointerException on 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();
}
}
将MockUp类型的定义移动到@Before方法:
public class MyBeanTest {
@Tested
DirBean tested;
@Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
@Mock
void init() {
}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}