使用构造函数为测试类进行依赖注入

时间:2018-03-27 11:32:45

标签: java unit-testing mockito

我的FixValueConceptIntegration类有一个构造函数,它看起来像这样:

private ReferenceConceptHelper referenceConceptHelper;

private ConceptClientFacade conceptClientExternalFacade;
public FixValueConceptIntegration()
{
  referenceConceptHelper = JournalSingletonFactory.getInstance().getSingletonInstance(ReferenceConceptHelper.class);
  conceptClientExternalFacade = JournalSingletonFactory.getInstance().getSingletonInstance(ConceptClientFacade.class);
}

所以现在我要使用Mockito进行测试。

如果我们有像

这样的构造函数
  public FixValueConceptIntegration(ReferenceConceptHelper referenceConceptHelper, ConceptClientFacade conceptClientExternalFacade)
  {
    this.referenceConceptHelper = referenceConceptHelper
    this.conceptClientExternalFacade = conceptClientExternalFacade
  }

我知道在我们测试课程时很容易初始化。因为我们可以模拟ReferenceConceptHelperConceptClientFacade类。 然后我们可以在@BeforeMethod这样使用它:

@BeforeMethod
public void beforeMethod()
{
  MockitoAnnotations.initMocks(this);
  fixValueConceptIntegration = new FixValueConceptIntegration(referenceConceptHelper, conceptClientExternalFacade);
}

然后所有依赖项将注入构造函数,无需担心。 所以这里的问题是我无法弄清楚如何将这些依赖项(通过模拟)注入上面的可测试类。

2 个答案:

答案 0 :(得分:1)

只需对类使用mockorg.mockito.Mockito.mock)方法,并使用when方法模拟方法调用:

@Test
public void yourTest() {

    ReferenceConceptHelper referenceConceptHelper = mock(ReferenceConceptHelper .class);
    when(referenceConceptHelper.someMethod(any()).thenReturn("hello");

    ConceptClientFacade conceptClientExternalFacade = mock(ConceptClientExternalFacade.class);
    when(conceptClientExternalFacade.someMethod(any()).thenReturn("world");

    FixValueConceptIntegration integration = new FixValueConceptIntegration(referenceConceptHelper, conceptClientExternalFacade);
    assertEquals("hello world", integration.methodThatYouWouldLikeToTest());
}

在这种情况下,您无需使用@BeforeMethod或致电MockitoAnnotations.initMocks(this);。对于单元测试,initMocks仅在您无法直接访问注入的类时(通常在使用场注入时)才有用。

但如果您想使用注释(我个人不喜欢),您可以这样做:

@InjectMocks
private FixValueConceptIntegration integration;

@Mock
private ReferenceConceptHelper referenceConceptHelper;

@Mock
private ConceptClientFacade conceptClientFacade;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    when(referenceConceptHelper.someMethod(any()).thenReturn("hello");
    when(conceptClientExternalFacade.someMethod(any()).thenReturn("world");
}

@Test
public void yourTest() {
    assertEquals("hello world", integration.methodThatYouWouldLikeToTest());
}

答案 1 :(得分:0)

我使用扩展TestNGBase的{​​{1}}扩展了我的测试类。 然后将PowerMockTestCase方法添加到registerMockSingleton类,就像这样;

TestNGBase

然后像这样向构造函数注入模拟依赖项;

protected <E, I extends E> void registerMockSingleton(Class<E> typeInterface, I mock)
  {
    delegate.registerMockSingleton(typeInterface, mock);
  }

全部解决了! (我的可测试类构造函数不会为构造函数注入依赖项  arguments.Thats为什么我这样解决了我的问题)