2016-12-14 111 views
0

我在测试数据休息库时遇到了问题。我打电话给休息资源,并检查它是否让我适当的JSON。但是对于不希望在内存数据库中使用的预填充数据,我嘲笑了库方法调用。
@MockBean private CommentRepository commentRepository; ,这样做,模拟弹簧数据休息库

given(commentRepository.findOne(1L)).willReturn(comment); 

而现在,一边拨打“/评论/ 1”我得到404错误,那么剩下的数据没有揭穿我的仓库。主要问题是“我们如何模拟仓库方法从数据库获取数据?”
我的测试类:

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
public class CommentTest 
{ 
    @Autowired 
    private TestRestTemplate restTemplate; 

    @MockBean 
    private CommentRepository commentRepository; 

    @Before 
    public void setup() 
    { 
    Comment comment = new Comment(); 
    comment.setText("description"); 
    comment.setCommentId(1L); 

    given(commentRepository.findOne(1L)).willReturn(comment); 
    } 

    @Test 
    public void shouldCheckCommentGetResource() 
    { 
    ParameterizedTypeReference<Resource<Comment>> responseType = new ParameterizedTypeReference<Resource<Comment>>() {}; 

    ResponseEntity<Resource<Comment>> responseEntity = 
     restTemplate.exchange("/comments/1", HttpMethod.GET, null, responseType, Collections 
      .emptyMap()); 

    Comment actualResult = responseEntity.getBody().getContent(); 
    assertEquals("description", actualResult.getText()); 
    // more assertions 
    } 
} 

据我了解,使用MockBean注解我替换当前仓库豆,它不会受到数据其余部分暴露出来,我们有什么办法可以预先填充的数据到数据库或模拟调用存储库方法?

+0

能你向我们展示你的测试和豆类? – dimitrisli

回答

0

我不认为这是可能的。 Spring数据使用FactoryBean注册存储库bean - 在spring-data-rest的情况下,这是EntityRepositoryFactoryBean。所以你不能只用模拟来覆盖这些bean。

有关为什么嘲笑春数据仓库一个有趣的阅读是没有用的看到这个答案https://stackoverflow.com/a/23442457/5371736

在同一个线程有一个项目引入对弹簧数据存储库的模拟支持参考 - https://stackoverflow.com/a/28643025/5371736