DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'jdbcTemplate' of type [null] on target object
@Transactional
@Repository
public class UserRepositoryImpl implements UserRepository {
public static final String FIND_BY_NAME = "select ut.user_id, ut.user_name, ut.user_password," +
" user_role.role_id, role_name from \n" +
"user_role inner join user_to_role\n" +
"on user_role.role_id = user_to_role.role_id \n" +
"inner join user_table as ut\n" +
"on ut.user_id = user_to_role.user_id\n" +
"where ut.user_name = ?";
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findByName(String userName) {
logger.info("find by name : {}", userName);
User user = jdbcTemplate.queryForObject(
FIND_BY_NAME,
(rs, rowNum) -> new User(
rs.getLong("user_id"),
rs.getString("user_name"),
rs.getString("user_password"),
Collections.singleton(new Role(
rs.getLong("role_id"),
rs.getString("role_name")
))),
userName);
if (Objects.isNull(user)) {
logger.info("Empty user");
return new User(); //test works if return setupUser();
} else {
return user;
}
}
}
@RunWith(MockitoJUnitRunner.class)
public class UserRepositoryImplTest {
@Mock
private UserRepositoryImpl userRepository;
@Before
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Test
public void findByNameTest() {
User user = setupUser();
String userName = user.getUserName();
JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
ReflectionTestUtils.setField(userRepository, "jdbcTemplate", jdbcTemplate);
// Mockito.when(jdbcTemplate.queryForObject(
// FIND_BY_NAME,
// new ForUnitTestUserRowMapper(),
// userName))
// .thenReturn(user);
Mockito.when(userRepository.jdbcTemplate.queryForObject(eq(FIND_BY_NAME),
any(ForUnitTestUserRowMapper.class),
anyString())).thenReturn(user);
assertEquals(user, userRepository.findByName(userName));
}
}
java.lang.AssertionError:
Expected :User{userId=1, userName='name', userPassword='password', roles=[Role{roleId=1, roleName='ROLE', users=null}]}
Actual :null