I know it is not a good thing write a unit test for mapper or get set but, it is what it is, so I am stucked how to do unit test for mappers;
StudentGroupList below;
@Getter
@Setter
public class StudentGroupList {
private String studentId;
}
StudentGroupListRowMapper below;
public class StudentGroupListRowMapper implements RowMapper<StudentGroupList> {
@Override
public StudentGroupList mapRow(Resultset rs, int rowNum) throws SQLException {
StudentGroupList studentGroupList = new StudentGroupList();
studentGroupList.setStudentId(rs.getString("student_id"));
return studentGroupList;
}
}
I have tried below, but jococo coverage test did not coverage anything
public class TaskGroupListRowMapperTest {
private ResultSet resultSet;
private StudentGroupList studentGroupList;
@Before
public void setUp() {
resultSet = mock(ResultSet.class);
studentGroupList = mock(StudentGroupList.class);
}
@Test
public void testStudentGroupListMapper() throws SQLException {
when(resultSet.getString("student_id"))
.thenReturn(studentGroupList.getStudentID());
assertTrue(studentGroupList.getStudentId(), true);
}
}
İt says exception; thenReturn() may be missing.
Take it easy, we were all there in the past and try to understand what a unit test is supposed to do.
You don't unit test everything just for the sake of unit test coverage. When you have a framework callback like RowMapper, it is one of those cases. Your StudentGroupListRowMapper
is very simple, so an integration test for your Dao will cover it. Anyway, you want to unit test so just think of it as a simple class and let's go through the steps.
You want to create the instance of the class you want to test and also provide mock dependencies for any services it calls. Luckily your StudentGroupListRowMapper
does not call anything. Since the method you want to test is StudentGroupList mapRow(ResultSet rs, int rowNum)
, you have to decide if you can provide a ResultSet
and a rowNum
. Since ResultSet
is not something you create, your provide a mock for that
ResultSet inputRs = mock(ResultSet.class);
int rowNum = 1;
inputRs.getString("student_id")
to get student id but it is mock and it doesn't know what to return so you have to tell your mock what to do when inputRs.getString("student_id")
is called when(inputRs.getString("student_id")).thenReturn("student-id-1");
StudentGroupList
should be created with "student-id-1"
and should be returned from the method.assertEquals(resultedStudentGroupList.getStudentId(),"student-id-1");
public class StudentGroupListRowMapperTest {
StudentGroupListRowMapper mapper = new StudentGroupListRowMapper();
@Test
public void testMapRow() {
ResultSet inputRs = mock(ResultSet.class);
int rowNum = 1;
when(inputRs.getString("student_id")).thenReturn("student-id-1");
StudentGroupList result = mapper.mapRow(inputRs, rowNum);
assertEquals(result.getStudentId(), "student-id-1");
}
}