我试图使用@mock将两个不同的对象注入我的类正在测试的类中。我需要它们是两个不同的对象,以便我可以在每个对象上使用when
来产生不同的结果。我搜索过的所有内容,因此指向此工作,但是在下面运行测试时 - 两个对象都是相同的模拟。
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)
@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());
}
}