我正在努力学习JUnit。处理特定问题我决定使用JUnitParams参数提供程序。测试方法I写入的每组参数应包含两个输入值和一个列表,对于该列表将测试方法调用的结果:
private static final Object[] getConstraints() {
return new Object[]{
new Object[]{15, Equipment.WHITEBOARD, Arrays.asList(new Classroom[]{classroomA, classroomB})},
new Object[]{15, Equipment.PROJECTOR, Arrays.asList(new Classroom[]{classroomB})},
new Object[]{15, Equipment.MICROPHONE, Arrays.asList(new Classroom[]{classroomA})},
new Object[]{30, Equipment.WHITEBOARD, Arrays.asList(new Classroom[]{classroomB})},
new Object[]{30, Equipment.PROJECTOR, Arrays.asList(new Classroom[]{classroomB})},
new Object[]{30, Equipment.MICROPHONE, Arrays.asList(new Classroom[]{})},
new Object[]{45, Equipment.WHITEBOARD, Arrays.asList(new Classroom[]{})},
new Object[]{45, Equipment.PROJECTOR, Arrays.asList(new Classroom[]{})},
new Object[]{45, Equipment.MICROPHONE, Arrays.asList(new Classroom[]{})},
};
}
classroomA
和classroomB
实际上是在每次测试执行之前准备好的Mockito存根:
@Before
public void setUp() {
classroomA = mock(Classroom.class);
classroomB = mock(Classroom.class);
classrooms = Arrays.asList(new Classroom[]{classroomA, classroomB});
when(classroomA.getName()).thenReturn("A");
when(classroomA.getCapacity()).thenReturn(20);
when(classroomA.getEquipment()).thenReturn(Arrays.asList(new Equipment[]{Equipment.WHITEBOARD, Equipment.MICROPHONE}));
when(classroomB.getName()).thenReturn("B");
when(classroomB.getCapacity()).thenReturn(40);
when(classroomB.getEquipment()).thenReturn(Arrays.asList(new Equipment[]{Equipment.WHITEBOARD, Equipment.PROJECTOR}));
bookingSystem = new BookingSystem(classrooms);
}
当我尝试使用上述Classroom
个对象列表时出现问题:
@Test
@Parameters(method = "getConstraints")
public void shouldBookClassroomMeetingConstraints(int capacity, Equipment equipment, List<Classroom>
suitableClassrooms) {
Assert.assertTrue("Should book a classroom that has a minimum capacity of " + capacity + " and has " +
equipment,
suitableClassrooms.contains(bookingSystem.book(capacity, equipment, ANY_DAY_OF_WEEK, ANY_HOUR)));
}
调试显示在第一次运行期间suitableClassrooms
包含2个对象,但进一步检查显示所有元素都为空 - 我准备的存根不存在。显然,测试不会通过或失败,应该通过或失败。
将MUnitParams与Mockito一起使用是否存在限制,或者我使用它们是错误的吗?使用它们的正确方法是什么?
这也可能是一种错误的单元测试技术。如果是这种情况,编写测试的正确方法是什么,以验证方法调用的结果是否在给定数组中?
答案 0 :(得分:4)
您测试不起作用,因为JUnitParamsRunner
跑步者在调用getConstraints
方法之前甚至在@Before
之前收集测试参数(即调用@BeforeClass
方法)。因此,classroomA
和classroomB
在此时为空。这就是suitableClassrooms
由null元素组成的原因。
解决方案是在classroomA
方法中初始化classroomB
和getConstraints()
。
我相信你可以在这里摆脱mockito。 Classroom
看起来像POJO,并且没有必要模拟POJO。在这种情况下,您只需创建Classroom
实例并填写必要的数据。
答案 1 :(得分:-2)
您需要让课程知道您正在使用Mockito运行测试用例。在课程级别添加以下内容,它应该可以正常工作。
@RunWith(MockitoJUnitRunner.class)