package com.siva.springboot.javaguruonline.repository; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.test.context.junit4.SpringRunner; import com.siva.springboot.javaguruonline.model.EmployeeDetails; @RunWith(SpringRunner.class) /** * * @author Siva * */ //@SpringBootTest(classes = SpringbootJpaSwaggerSonarqubeApplication.class) public class EmployeeDaoImplTest { @InjectMocks public EmployeeDaoImpl employeeDao; @Mock private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @SuppressWarnings("unchecked") @Test public void testGetAllEmployeeDetails(){ Listlist = new ArrayList (); EmployeeDetails employeeDetails = new EmployeeDetails(); employeeDetails.setEmpId(1); employeeDetails.setEmpName("siva"); list.add(employeeDetails); Mockito.when(namedParameterJdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))) .thenAnswer(new Answer >() { @Override public List
answer(InvocationOnMock invocation) throws Throwable { // Fetch the method arguments Object[] args = invocation.getArguments(); // Fetch the row mapper instance from the arguments RowMapper rm = (RowMapper ) args[1]; // Create a mock result set and setup an expectation on it ResultSet rs = Mockito.mock(ResultSet.class); Mockito.when(rs.getInt("emp_id")).thenReturn(employeeDetails.getEmpId()); Mockito.when(rs.getString("emp_name")).thenReturn(employeeDetails.getEmpName()); // Invoke the row mapper EmployeeDetails actual = rm.mapRow(rs, 0); // Assert the result of the row mapper execution Assert.assertEquals(employeeDetails.getEmpName(), actual.getEmpName()); // Return your created list for the template#query call return list; } }); employeeDao.getEmployeeDetails(); Assert.assertNotNull(list); } }
Showing posts with label JDBC Resultset Mock. Show all posts
Showing posts with label JDBC Resultset Mock. Show all posts
Thursday, March 11, 2021
How to mock ResultSet , NamedParameterJdbcTemplate , RowMapper
Subscribe to:
Posts (Atom)