【发布时间】:2015-06-01 20:50:48
【问题描述】:
我有这个代码:
class Patient {
@Inject Syringe syringe;
@PostConstruct
void sayThankyouDoc() {
System.out.println("That hurt like crazy!");
}
}
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
@InjectMocks
Patient patient;
//...
}
我预计 Mockito 会调用 PostConstruct,但我必须添加:
@Before
public void simulate_post_construct() throws Exception {
Method postConstruct = Patient.class.getDeclaredMethod("sayThankyouDoc", null);
postConstruct.setAccessible(true);
postConstruct.invoke(patient);
}
有没有更好的方法来做到这一点?
【问题讨论】:
-
另一种更具可读性和更易于测试的设计是根本不使用
@PostConstruct,而是使用构造函数注入而不是字段注入 -
@geoand 但是是构造函数注入是什么?
标签: java junit mockito cdi postconstruct