java - JMockit 在 @PostConstruct 中模拟私有(private)方法

标签 java unit-testing jakarta-ee junit jmockit

上下文

在我的测试类中,有一个 @PostConstruct 带注释的方法调用另一个私有(private)方法。

@PostConstruct
public void init() {
    longWork(); // private method
}

JMockit 的默认行为是在注入(inject)时执行 @Tested 类的 @PostConstruct 方法。

If a @Tested class has a method annotated with javax.annotations.PostConstruct, it should be executed right after injection.

https://github.com/jmockit/jmockit1/issues/13

问题

JMockit 调用 init() 方法,这是我不想要的。

来自线程转储:

at com.me.Worker.longWork(Worker.java:56)
at com.me.Worker.longWork.init(Worker.java:47)
...
at mockit.internal.util.MethodReflection.invoke(MethodReflection.java:96)

如何模拟/删除/阻止该调用?

尝试

我尝试模拟 initlongWork 方法,如下所示。但是,这会导致 NullPointerException,因为 sut 尚未注入(inject)。

@Before
public void recordExpectationsForPostConstruct()
{
    new NonStrictExpectations(sut) {{ invoke(sut, "init"); }};
}

最佳答案

您可以尝试手动初始化要测试的类,而不使用@Tested。然后,通过setter方法(或使用mockit.Deencapsulation.setField()方法)设置模拟依赖项。

您可以尝试类似的方法;

//Define your class under test without any annotation
private MyServiceImpl serviceToBeTested;

//Create mock dependencies here using @Mocked like below
@Mocked Dependency mockInstance;



@Before
public void setup() {
    //Initialize your class under test here (or you can do it while declaring it also). 
    serviceToBeTested = new MyServiceImpl();

    //Set dependencies via setter (or using mockit.Deencapsulation.setField() method)
    serviceToBeTested.setMyDependency(mockInstance);

    //Optionally add your expectations on mock instances which are common for all tests
    new Expectations() {{
        mockInstance.getName(); result = "Test Name";
        ...
    }};
}

@Test
public void testMyMethod(@Mocked AnotherDependency anotherMock) {
    //Add your expectations on mock instances specifics to this test method.
    new Expectations() {{
        mockInstance.getStatus(); result = "OK";
        anotherMock.longWork(); result = true;
        ...
    }};

    //Set dependencies via setter or using mockit.Deencapsulation.setField() method
    Deencapsulation.setField(serviceToBeTested, "myAnotherDep", anotherMock);

    //Invoke the desired method to be tested
    serviceToBeTested.myMethod();

    //Do the verifications & assertions
    new Verifications() {{
      ....
      ....

    }};

}

关于java - JMockit 在 @PostConstruct 中模拟私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336105/

相关文章:

unit-testing - c 程序的 Concolic 测试

unit-testing - 需要将文件部署到 TestInitialize() 中使用的 MSTest 影子目录

java - 如何在 Java EE 中编写 cron 作业?

java - 如何在 JSP 中访问 JSONArray 元素

java - 组织导入 Eclipse 方法

java - 具有重复节点名称的 xml 解析

java - Accept-Language header 和 ResourceBundle 之间缺少功能

java字节数组转字符串

php - 从工作单元测试用例构建简单测试套件的麻烦

java - Arquillian 与 Glassfish V4