I want to test CRUD Repository with related JPQL:
@Repository
public interface UserRolesRepository extends CrudRepository<UserRoles, Long> {
@Query("SELECT a.role FROM UserRoles a, UserEntity b WHERE b.username=?1 AND a.id=b.id")
public List<String> findRoleByUserName(String name);
}
My problem is to mock repository related to UserEntity. I've tried to mock methods of user repository, but them seem not to be ever called.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BlogCmsApplication.class)
public class UserRolesRepositoryTest {
@Autowired
UserRolesRepository userRolesRepository;
@Mock
UserRepository userRepository;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void findRoleByUserName() throws Exception {
UserEntity user = new UserEntity("user467","somepass");
user.setId(1);
Mockito.when(userRepository.findByUsername(user.getUsername())).thenReturn(user);
Mockito.when(userRepository.findOne(user.getId())).thenReturn(user);
Mockito.when(userRepository.exists(user.getId())).thenReturn(true);
UserRoles role = new UserRoles(1,"ROLE_USER");
userRolesRepository.save(role);
List<String> actualRole;
actualRole = userRolesRepository.findRoleByUserName(user.getUsername());
List<String> expectedRole = new ArrayList<>();
expectedRole.add(role.getRole());
assertNotNull(actualRole);
assertEquals(expectedRole,actualRole);
}
With @Autowired
works fine but it's not the point. Assertion error is
Expected :[ROLE_USER]
Actual :[]
Aucun commentaire:
Enregistrer un commentaire