我正在尝试将测试用例的第一个代码块简化为第二个代码块中显示的类似内容。 我有两个问题:
类似的事情是否可以实现?
@Test
public void testStudentSuccess() {
Student st = new Student();
st.setRollNumber("1234");
st.setFeeAmount("1000");
List<Student> stList = new ArrayList<Student>();
stList.add(st);
Map<String, Object> simpleJdbcCallResult = new HashMap<String, Object>();
simpleJdbcCallResult.put("X_GET_DATA", stList);
when(simpleJdbcCall.getSimpleJdbcCall(any(String.class), any(String.class), any(String.class),
any(String.class), any(String.class), any(String.class), any(String.class), any(String.class),
any(StudentRowMapper.class))).thenReturn(simpleJdbcCallResult);
List<Student> studentList = opusPackageRepo.getPolicyStudent("123", "123");
Student student = studentList.get(0);
assertEquals(student.getRollNumber(), "1234");
assertEquals(student.getFeeAmount(), "1000");
}
这样的事情(见评论 - &gt; //):
@Test
public void testStudentSuccess() {
List<Student> stList = Mockito.mock(new ArrayList<Student>()); // 1. IS SOMTHING SIMILAR TO THIS POSSIBLE?
Map<String, Object> simpleJdbcCallResult = new HashMap<String, Object>();
simpleJdbcCallResult.put("X_GET_DATA", Mockito.mock(new ArrayList<Student>()));
when(simpleJdbcCall.getSimpleJdbcCall(any(String.class), any(String.class), any(String.class),
any(String.class), any(String.class), any(String.class), any(String.class), any(String.class),
any(StudentRowMapper.class))).thenReturn(simpleJdbcCallResult);
List<Student> studentList = opusPackageRepo.getPolicyStudent("123", "123");
assertEquals(studentList, stList); // 2. CAN I ASSERT EQUALS A MOCK WITH A RETURNED LIST?
}
答案 0 :(得分:1)
在OP的原始测试中,您正在为simpleJdbcCall.getSimpleJdbcCall()
创建预期结果,如下所示:
Student st = new Student();
st.setRollNumber("1234");
st.setFeeAmount("1000");
List<Student> stList = new ArrayList<Student>();
stList.add(st);
Map<String, Object> simpleJdbcCallResult = new HashMap<String, Object>();
simpleJdbcCallResult.put("X_GET_DATA", stList);
然后断言结果(opusPackageRepo.getPolicyStudent()
必须通过"X_GET_DATA"
键访问)符合您的期望:
Student student = studentList.get(0);
assertEquals(student.getRollNumber(), "1234");
assertEquals(student.getFeeAmount(), "1000");
你可以在不需要考虑嘲笑的情况下简化这一点......
List<Student> expected = new ArrayList<Student>();
Map<String, Object> simpleJdbcCallResult = new HashMap<String, Object>();
simpleJdbcCallResult.put("X_GET_DATA", expected);
...
List<Student> actual = opusPackageRepo.getPolicyStudent("123", "123");
assertSame(expected, actual);
这将验证getPolicyStudent
返回的结果与simpleJdbcCall.getSimpleJdbcCall()
调用返回的列表相同。
您的测试不需要知道此列表的内容,因为您的测试仅涉及验证simpleJdbcCall.getSimpleJdbcCall()
返回的列表是否被getPolicyStudent
从此键读取时正确传递: "X_GET_DATA"
。我认为这是你在写“简化测试用例”时所暗示的,它可以轻松完成但不需要任何模拟。