【发布时间】:2017-07-12 16:58:14
【问题描述】:
我已经阅读了很多文章/博客/StackOverflow 问题,但关于 Mockito 模拟和间谍的困惑仍然存在。所以,我开始尝试在一个小的Spring Boot 应用程序中实现它们。我的应用程序有一个 ProductRepository 扩展 CrudRepository。
目前我正在通过模拟ProductRepository 来测试存储库,如下所示
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RepositoryConfiguration.class})
public class ProductRepositoryMockTest {
@Mock
private ProductRepository productRepository;
@Mock
private Product product;
@Test
public void testMockCreation(){
assertNotNull(product);
assertNotNull(productRepository);
}
@Test
public void testSaveProduct() {
assertThat(product.getId(), is(equalTo(0)));
when(productRepository.save(product)).thenReturn(product);
productRepository.save(product);
//Obviously this will fail as product is not saved to db and hence
//@GeneratedValue won't come to play
//assertThat(product.getId() , is(not(0)));
}
@Test
public void testFindProductById() {
when(productRepository.findOne(product.getId())).thenReturn(product);
assertNotNull(productRepository.findOne(product.getId()));
assertEquals(product, productRepository.findOne(product.getId()));
}
}
测试通过。这是正确的方法吗?我也想了解如何在这里使用@Spy 以及为什么需要它?任何与此相关的特定场景都非常受欢迎。
提前致谢。
【问题讨论】:
-
不要对你的存储库进行单元测试。关注单元测试的服务层。如果您的存储库中有一些逻辑,那么这可能是一个设计缺陷。
-
是的,明白了。谢谢。
-
@Maciej Kowalski 最后设法根据您的输入使用模拟和间谍来测试服务层。但不知道我是否做得正确,我的仓库位于github.com/ximanta/mockito_spy_example 您的观察将很有价值。如果需要,可以将其作为问题发布。谢谢。
-
我检查了 repo.. 看看我的答案
标签: java unit-testing spring-boot junit mockito