java – 如何使用“Spring Data JPA”规范单元测试方法

我正在玩org.springframework.data.jpa.domain.Specifications,它只是一个基本的搜索

 public OptionalgaliteCode(code)).and(ArticleSpecifications.egaliteLibelle(libelle)));
    }else{
        if(StringUtils.isNotEmpty(code)){
            result= articleRepository.findAll(Specifications.where(ArticleSpecifications.egaliteCode(code)));
        }else{
            result = articleRepository.findAll(Specifications.where(ArticleSpecifications.egaliteLibelle(libelle)));
        }
    }

    if(result.isEmpty()){
        return Optional.empty();
    }else{
        return Optional.of(result);
    }
}

这实际上工作正常,但我想为这个方法编写单元测试,我无法弄清楚如何检查传递给我的articleRepository.findAll()的规范

目前我的单元测试看起来像:

@Test
public void rechercheArticle_okTousCriteres() throws FacturationServiceException {
    String code = "code";
    String libelle = "libelle";
    ListgaliteCode(code)).and(ArticleSpecifications.egaliteLibelle(libelle)));
    //argument.getValue().toPredicate(root,query,builder);


}

任何的想法?

最佳答案
我遇到了几乎和你一样的问题,并且我将包含规范的类更改为一个对象而不是一个静态方法的类.这样我就可以轻松地模拟它,使用依赖注入来传递它,并测试调用哪些方法(不使用powermockito来模拟静态方法).

如果你想像我一样做,我建议你用集成测试测试规范的正确性,其余的,只要调用正确的方法.

例如:

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());
    Listpecs.calledBetween(firstDayOfMonth,lastDayOfMonth));
    assertthat(cdrList).isNotEmpty().hasSize(2);
}

现在,当您想要对其他组件进行单元测试时,您可以像这样进行测试,例如:

@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方法.

我希望这可以帮到你.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...