我遇到了一个问题,其中对于@InjectMocks
Mockito的@Mock
注释的现场注入匹配在存在相同类型的2个@Mock
的情况下不起作用。我已经使用了@Mock (name = "name_of_var")
语法为好,但它还是没有......为什么在使用PowerMockRunner运行时无法使用@InjectMocks字段匹配?
下面是测试类:
import java.util.Date;
public class Parent{
private Date dateA;
private Date dateB;
public void setDateA(Date _dateA){
dateA = _dateA;
}
public void setDateB(Date _dateB){
dateB = _dateB;
}
public Date getDateA(){
return dateA;
}
public Date getDateB(){
return dateB;
}
下面是测试本身:
@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class, Parent.class})
public class testParent{
@Mock (name = "dateB") private Date someOtherDate;
@Mock (name = "dateA") private Date someDate;
@InjectMocks Parent p;
@Before
public void setup(){
Mockito.when(someOtherDate.getTime()).thenReturn(500l);
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(2000l);
}
@Test
public void testGetDateAGetTimeShouldReturn1000() {
Mockito.when(someDate.getTime()).thenReturn(1000l);
Date result = p.getDateA();
assertEquals(1000l, result.getTime());
}
@Test
public void testGetDateBGetTimeShouldReturn500() {
Date result = p.getDateB();
assertEquals(500l, result.getTime());
}
测试时,由于@InjectMocks
不起作用,两个assertEquals
都会导致NullPointerException
。
现在,当我用@RunWith(MockitoJUnitRunner.class)
代替@RunWith(PowerMockRunner.class)
时,它工作得很好。
另外,如果我刚刚定义的Parent.java
1个Date
变量(比如,dateA
)和匹配模拟在ParentTest
注入,它只是罚款使用PowerMockRunner.class
注入。
我必须运行PowerMockRunner.class的原因是我必须能够模拟静态函数以及构造函数。
我正在使用Junit4.12,Mockito-all-1.10.19和PowerMock-mockito-1.6.2-full。
有没有人看到为什么它不能正确注射的原因是PowerMockRunner.class
? PowerMockRunner.class
运行时有没有解决方法?