在我的测试类中,有一个@PostConstruct
带注释的方法可以调用另一个私有方法。
@PostConstruct
public void init() {
longWork(); // private method
}
JMockit的默认行为是在注入时执行@PostConstruct
类的@Tested
方法。
如果@Tested类有一个带注释的方法 javax.annotations.PostConstruct,它应该在之后执行 注射。
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)
如何嘲笑/删除/阻止该呼叫?
我试图模仿init
和longWork
方法,如下所示。但是,NullPointerException
导致sut
尚未注入。
@Before
public void recordExpectationsForPostConstruct()
{
new NonStrictExpectations(sut) {{ invoke(sut, "init"); }};
}
答案 0 :(得分:2)
您可以尝试手动初始化要测试的类,而无需使用@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() {{
....
....
}};
}
答案 1 :(得分:0)
也许您可以将longWork方法委托给另一个类并模拟这个类。编写测试时遇到的困难往往是设计缺陷的标志