简体   繁体   English

在@Rule运行之前如何使用Guice在Junit测试用例中注入依赖项?

[英]How do I inject dependencies in Junit test case using Guice before @Rule runs?

Frameworks I'm working with are Dropwizard 7, Guice and for testing we have Junit with Jukito. 我正在使用的框架是Dropwizard 7,Guice,为了测试我们有Junit和Jukito。 I have a resource written in dw and I need to write a test case corresponding to that resource. 我有一个用dw编写的资源,我需要编写一个与该资源相对应的测试用例。 Note: We recently migrated from dw 6 to dw 7. 注意:我们最近从dw 6迁移到dw 7。

In dw 6 we had test cases like : 在dw 6中我们有测试用例,例如:

@RunWith(JukitoRunner.class)
public class AbcResourceTest extends ResourceTest{
  @Inject
  private Provider<XyzAction> xyzProvider;
  public void setUpResources() throws Exception {
   addResource(new AbcResource(xyzProvider));
  }
  @Test
  public void doTesting() {
  }
}

This method worked just fine, Guice would inject all the dependency and the resource would initialise just fine. 这个方法工作得很好,Guice会注入所有依赖项,资源初始化就好了。

But in DW 7 the syntax for writing resource test changed to the following 但在DW 7中,编写资源测试的语法更改为以下内容

public class ResourceTest {
 PersonDao personDao = mock(PersonDao.class);
 @Rule public ResourceTestRule resources = ResourceTestRule
      .builder()
      .addResource(new Resource(personDao))
      .build();
}

This is an example from the dw documentation and works fine. 这是dw文档中的一个示例,工作正常。 But if instead of mocking PersonDao if i try to inject something like this: 但如果我尝试注入这样的东西,而不是嘲笑PersonDao:

@RunWith(JukitoRunner.class)
public class AbcResourceTest {
  @Inject
  private Provider<XyzAction> xyzProvider;
 @Rule public ResourceTestRule resources = ResourceTestRule
      .builder()
      .addResource((new AbcResource(xyzProvider))
      .build();
  @Test
  public void doTesting() {
  }
}

This code instantiates the resource with null value for xyzProvider. 此代码实例化xyzProvider的空值资源。 Although Guice does instantiates the xyzProvider but only after @Rule has been evaluated. 虽然Guice确实实例化了xyzProvider,但只有在评估了@Rule之后。 Now my problem is that i want Guice to inject dependency before @Rule is evaluated. 现在我的问题是我希望Guice在评估@Rule之前注入依赖。 Is there a way to make that happen? 有没有办法让这种情况发生?

I suspect that JukitoRunner will cause injection to happen before the @Rule runs . 我怀疑JukitoRunner会在@Rule 运行之前引起注射。 But what it can't do is cause injection to happen before the constructor finishes . 但它不能做的是在构造函数完成之前导致注入。 Something like this might work (Java 8 syntax): 这样的东西可能会起作用(Java 8语法):

@Inject
private XyzAction xyz;

@Rule
public ResourceTestRule resources = ResourceTestRule
        .builder()
        .addResource(new AbcResource(() -> xyz))
        .build();

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

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