【发布时间】:2017-04-30 10:48:59
【问题描述】:
我在测试数据存储库时遇到了问题。我打电话给休息资源并检查它是否让我得到正确的json。但是对于我不想在内存数据库中使用的预填充数据,所以我模拟了存储库方法调用。@MockBean
private CommentRepository commentRepository;
并做到了这一点
given(commentRepository.findOne(1L)).willReturn(comment);
现在,在调用“/cmets/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 注释我替换了当前存储库 bean,它不会被数据休息暴露,我们有没有办法将数据预填充到 db 或模拟调用存储库方法?
【问题讨论】:
-
你能给我们看看你的测试和豆子吗?
标签: spring rest unit-testing spring-data-rest