gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:03:40 28 4
gpt4 key购买 nike

上下文

在我的测试类中,有一个 @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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com