Tại sao mockMap
sử dụng triển khai thực sự? Làm cách nào để ngăn chặn điều này?Đối tượng giả Mockito sử dụng thực hiện thực tế
Trong phương pháp testFirstKeyMatch
when(mockMap.keySet().toArray()[0])...
ném ArrayIndexOutOfBoundsException: 0 khi chạy thử nghiệm.
MaxSizeHashMap là LinkedHashMap có kích thước tối đa là 7, ném ra một IndexOutOfBoundsException khi tôi cố gắng thêm vào.
Tiểu sử theo dõi thứ gì đó không cần thiết cho việc này.
SuperClass.java
public class SuperClass {
protected String[] days;
protected MaxSizeHashMap<String, String> map;
public SuperClass() {
days = new String[7];
map = new MaxSizeHashMap<String, String>();
//...
}
void updateDays() {
cal = Calendar.getInstance();
for (int i = 0; i < 7; i = i + 1) {
//adds short names "Mon", "Tue", ... to days
days[i] = cal.getDisplayName(Calendar.DAY_OF_WEEK,
Calendar.SHORT, Locale.US);
cal.add(Calendar.DATE, 1);
}
}
void firstKeyMatch(Profile profile) {
updateDays();
//checks if first key of map is not same as days[0]
if (days[0] != map.keySet().toArray()[0]) {
profile.add();
//...
}
}
}
SuperClassTest.java
@RunWith(MockitoJUnitRunner.class)
public class SuperClassTest {
@InjectMocks
private SuperClass spr = new SuperClass();
@Mock
private MaxSizeHashMap<String, String> mockMap;
@Mock
private Profile mockProfile;
//...
@Test
public void testFirstKeyMatch() {
when(mockMap.keySet().toArray()[0]).thenReturn(spr.days[0]);
verify(mockProfile, never()).add();
}
}
Hãy thử này 'khi (mockMap.keySet()). thenReturn (new HashSet (Arrays.asList ("chuỗi ngày của bạn"))); 'bằng cách thay thế" chuỗi ngày của bạn "với bất kỳ giá trị nào bạn đang thử nghiệm với – Abubakkar
Nó không phải là thực hiện thực, mocks trả về giá trị mặc định. Trong trường hợp 'keySet()', nó là một tập hợp rỗng. – Jonathan