Jmockit和@PostConstruct bean

时间:2016-10-17 14:51:46

标签: java java-ee jmockit postconstruct

我已经用我想要测试的方法创建了一个bean。不幸的是,它是一个带有PostConstruct注释的bean。我不想调用PostConstruct方法。 我怎样才能做到这一点?

我尝试了两种不同的方式(如下例所示)但没有工作; init()仍然被调用。

有人可以给我一个如何做到这一点的详细例子吗?

DirBean.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();
    }
}

MyBeanTest.java

public class MyBeanTest2 {

    @Tested
    DirBean tested;

    @Before
    public void recordExpectationsForPostConstruct() {
       new MockUp<DirBean>() {
            @Mock
            void init() {}
       };
    }

    @Test
    public void testMyDirBeanCall() {
        tested.methodIwantToTest();
    }
}

MyBeanTest2.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();
    }
}

MyBeanTest3.java(WORKS)

public class MyBeanTest4 {

    @Tested
    DirBean tested;

    @Before
    public void recordExpectationsForCallsInsideInit() {
        new Expectations(tested) {
        {
            Deencapsulation.invoke(tested, "methodCalledfromInit", anyInt);
        }
        };
    }

    @Test
    public void testMyDirBeanCall() {
        tested.methodIwantToTest();
    }
}

MyBeanTest4.java(在invoke()上使用NullPointerException的FAILS)

src/main/resources

1 个答案:

答案 0 :(得分:3)

将MockUp类型的定义移至@Before方法:

public class MyBeanTest {

    @Tested
    DirBean tested;

    @Before
    public void recordExpectationsForPostConstruct() {
        new MockUp<DirBean>() {
            @Mock
            void init() {
            }
        }; 
    }

    @Test
    public void testMyDirBeanCall() {
        tested.methodIwantToTest();
    }
}