我遇到了一個問題,其中對於@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
運行時有沒有解決方法?