我有这个代码:
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);
}
有更好的方法吗?
最佳答案
虽然不是您问题的直接答案,但我建议您放弃字段注入(inject)并改用构造函数注入(inject)(使代码更具可读性和可测试性)。
您的代码如下所示:
class Patient {
private final Syringe syringe;
@Inject
public Patient(Syringe syringe) {
System.out.println("That hurt like crazy!");
}
}
那么您的测试将只是:
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
Patient patient;
@Before
public void setup() {
patient = new Patient(siringeMock);
}
}
更新
根据 Erik-Karl 的建议在评论中,您可以使用 @InjectMocks
来摆脱设置方法。该解决方案之所以有效,是因为 Mockito 将使用适当的构造函数注入(inject)(如 here 所述)。
代码将如下所示:
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
@InjectMocks
Patient patient;
}
关于java - Mockito 和 CDI bean 注入(inject),@InjectMocks 调用@PostConstruct 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29319106/