微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我希望这可以帮到你.

原文地址:https://www.jb51.cc/spring/432325.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐