Mockito 和 CDI bean 注入,@InjectMocks 调用@PostConstruct 吗?

Mockito and CDI bean injection, does @InjectMocks call @PostConstruct?

我有这个代码:

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);
}

有更好的方法吗?

虽然不是您问题的直接答案,但我建议您放弃字段注入并改用构造函数注入(使代码更具可读性和可测试性)。

您的代码如下所示:

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 in the comments, you could use @InjectMocks to get rid of the setup method. The solution works because Mockito will use the appropriate constructor injection (as described here 所建议)。 代码将如下所示:

@RunWith(MockitoJUnitRunner.class)
class TestCase {

  @Mock
  Syringe siringeMock;

  @InjectMocks
  Patient patient;

}