我在测试数据休息库时遇到了问题。我打电话给休息资源,并检查它是否让我适当的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注解我替换当前仓库豆,它不会受到数据其余部分暴露出来,我们有什么办法可以预先填充的数据到数据库或模拟调用存储库方法?
能你向我们展示你的测试和豆类? – dimitrisli