我已经用我想测试的方法创建了一个bean。不幸的是,它是一个带有PostConstruct注释的bean。我不想调用PostConstruct方法。我该怎么做?
我尝试过两种不同的方法(如下面的示例所示),但是没有一种方法起作用;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 (WORKS)
public class MyBeanTest2 {
@Tested
DirBean tested;
@Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
@Mock
void init() {}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}MyBeanTest3.java (WORKS)
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失败)
public class MyBeanTest4 {
@Tested
DirBean tested;
@Before
public void recordExpectationsForCallsInsideInit() {
new Expectations(tested) {
{
Deencapsulation.invoke(tested, "methodCalledfromInit", anyInt);
}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}发布于 2016-10-17 15:32:18
将MockUp类型的定义移动到@ type方法:
public class MyBeanTest {
@Tested
DirBean tested;
@Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
@Mock
void init() {
}
};
}
@Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}https://stackoverflow.com/questions/40089568
复制相似问题