测试时由JPQL查询使用的模拟存储库

时间:2016-08-31 07:40:30

标签: java spring unit-testing junit mockito

我想用相关的JPQL测试CRUD存储库:

@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);
}

我的问题是模拟与UserEntity相关的存储库。我试图模拟用户存储库的方法,但它们似乎从未被调用过。

@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);

}

@Autowired工作正常,但不重要。 断言错误是

Expected :[ROLE_USER]
Actual   :[]

1 个答案:

答案 0 :(得分:0)

是的,您可以在这里使用@MockBean,Spring Boot包含一个@MockBean注释,可用于为bean定义Mockito模拟 在ApplicationContext中。您可以使用注释添加新bean,或替换单个bean 现有的bean定义。注释可以直接用于测试类,测试中的字段, 或@Configuration类和字段。在字段上使用时,创建的模拟的实例将 也是注射。每种测试方法后,模拟豆会自动重置。

@RunWith(SpringRunner.class)
@DataJpaTest
@Transactional
public class SpringBootJPATest {

    @MockBean
    private BlogEntryRepository blogEntryRepository;

    @Autowired
    private TestEntityManager entityManager;

    @Test
    public void jpa_test() {
        BlogEntry entity = new BlogEntry();
        entity.setTitle("Test Spring Boot JPA Test");
        BlogEntry persist = entityManager.persist(entity);
        System.out.println(persist.getId());
    }

    @Test
    public void jap_test_repo() {
        BlogEntry entity = new BlogEntry();
        entity.setTitle("Test Spring Boot JPA Test");
        BlogEntry persist = blogEntryRepository.save(entity);
        // System.out.println(persist.getId()); // This line will get a NPE as the repo is using the mocked bean
    }
}