繁体   English   中英

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在评论中所建议的那样,你可以使用@InjectMocks来摆脱设置方法。 解决方案的工作,因为会的Mockito使用适当的构造函数注入(如描述在这里 )。 然后代码看起来像:

@RunWith(MockitoJUnitRunner.class)
class TestCase {

  @Mock
  Syringe siringeMock;

  @InjectMocks
  Patient patient;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM