Jmockit 和@PostConstruct bean

Jmockit and @PostConstruct bean

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

我尝试了 2 种不同的方法(如下例所示),但 none 有效; 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 失败)

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