我正在玩org.springframework.data.jpa.domain.Specifications,它只是一个基本的搜索:
public Optional
这实际上工作正常,但我想为这个方法编写单元测试,我无法弄清楚如何检查传递给我的articleRepository.findAll()的规范
目前我的单元测试看起来像:
@Test
public void rechercheArticle_okTousCriteres() throws FacturationServiceException {
String code = "code";
String libelle = "libelle";
List
任何的想法?
最佳答案
我遇到了几乎和你一样的问题,并且我将包含规范的类更改为一个对象而不是一个静态方法的类.这样我就可以轻松地模拟它,使用依赖注入来传递它,并测试调用哪些方法(不使用PowerMockito来模拟静态方法).
原文链接:https://www.f2er.com/spring/432325.html如果你想像我一样做,我建议你用集成测试测试规范的正确性,其余的,只要调用正确的方法.
例如:
public class CdrSpecs {
public Specification
然后,您对此方法进行了集成测试,该测试将测试该方法是否正确:
@RunWith(SpringRunner.class)
@DataJpaTest
@sql("/cdr-test-data.sql")
public class CdrIntegrationTest {
@Autowired
private CdrRepository cdrRepository;
private CdrSpecs specs = new CdrSpecs();
@Test
public void findByPeriod() throws Exception {
LocalDateTime today = LocalDateTime.now();
LocalDateTime firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDateTime lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
List
现在,当您想要对其他组件进行单元测试时,您可以像这样进行测试,例如:
@RunWith(JUnit4.class)
public class CdrSearchServiceTest {
@Mock
private CdrSpecs specs;
@Mock
private CdrRepository repo;
private CdrSearchService searchService;
@Before
public void setUp() throws Exception {
initMocks(this);
searchService = new CdrSearchService(repo,specs);
}
@Test
public void testSearch() throws Exception {
// some code here that interact with searchService
verify(specs).calledBetween(any(LocalDateTime.class),any(LocalDateTime.class));
// and you can verify any other method of specs that should have been called
}
当然,在服务内部,您仍然可以使用规范类的where和static方法.
我希望这可以帮到你.