Mockito @Mock无法使用构造函数注入正确注入命名的模拟

时间:2018-12-19 23:13:03

标签: java unit-testing mockito

我正在尝试使用@Mock将两个不同的对象注入到我的受测类中。我需要它们是两个不同的对象,以便可以在每个对象上使用when来产生不同的结果。我在SO上搜索的所有内容都指向此工作,但是在进行以下测试时-两个对象都是同一模拟。

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import com.ihm.pp.test.UnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

/**
 * @author Josh Johnston
 */
@Category(UnitTest.class)
@RunWith(MockitoJUnitRunner.class)
public class ConstructorInjectionBug {

  @Mock
  private IBroken aBroken;

  @Mock
  private IBroken bBroken;

  @InjectMocks
  private UsesBroken usesBroken;

  @Test
  public void testBrokenConstructorInjection() {

    when(bBroken.getNumber()).thenReturn(2);
    assertEquals(2, usesBroken.getbBroken().getNumber());

    when(aBroken.getNumber()).thenReturn(1);
    assertEquals(1, usesBroken.getaBroken().getNumber());
  }
}

interface IBroken {
  int getNumber();
}

class UsesBroken {

  private IBroken aBroken;
  private IBroken bBroken;

  public UsesBroken(IBroken aBroken, IBroken bBroken) {
    this.aBroken = aBroken;
    this.bBroken = bBroken;
  }

  public IBroken getaBroken() {
    return aBroken;
  }

  public IBroken getbBroken() {
    return bBroken;
  }
}

结果:

java.lang.AssertionError:
    Expected :1
    Actual   :2

at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:645)
    at org.junit.Assert.assertEquals(Assert.java:631)
    at ConstructorInjectionBug.testBrokenConstructorInjection(ConstructorInjectionBug.java:37)

1 个答案:

答案 0 :(得分:3)

@InjectMocks将不知道要注入哪个IBroken。因此,并不是说它坏了,而是设计上有缺陷。

您需要将模拟对象显式注入被测对象中,以获得所需的行为。

@Category(UnitTest.class)
@RunWith(MockitoJUnitRunner.class)
public class ConstructorInjectionBug {

  @Mock
  private IBroken aBroken;

  @Mock
  private IBroken bBroken;

  private UsesBroken usesBroken;

  @Test
  public void testBrokenConstructorInjection() {
    //Arrange
    usesBroken = new UsesBroken(aBroken, bBroken);
    when(bBroken.getNumber()).thenReturn(2);
    when(aBroken.getNumber()).thenReturn(1);

    //Act & Assert
    assertEquals(2, usesBroken.getbBroken().getNumber());    
    assertEquals(1, usesBroken.getaBroken().getNumber());
  }
}