使用TestEntityManager测试JPA查询

时间:2019-03-28 09:43:58

标签: spring-boot testing junit h2

我有一个服务,可以获取复杂的JPAQueries。我必须为此服务编写h2数据库测试。此“获取”服务中的自动装配服务将构建JPAQueries。因此,我必须模拟此自动装配服务,并且必须为获取服务返回BuiltQuery。我为此做了Baeldung的教程,这说我必须使用TestEntityManager。现在,我想构建JPAQuery以返回被模拟的QueryBuilderService。当我做

new JPAQuery(entityManager)

它希望EntityManager作为参数,而不是TestEntityManager。

有人对此有好的解决方案吗?是否存在类似“ TestJPAQuery”之类的东西?请帮忙:)

有人要求提供我要测试的代码:

@Service()
public class TnsTicketLoaderService extends TnsBaseService implements ITnsTicketLoaderService{

private ITnsTicketQueryBuilder ticketQueryBuilder;

    public TnsTicketLoaderService(ITnsTicketQueryBuilder ticketQueryBuilder) {
        this.ticketQueryBuilder = ticketQueryBuilder;
    }

@Override
    public List<TnsTicket> loadTickets(TnsTicketConfiguration ticketConfiguration) {
        return this.buildQuery(ticketConfiguration).fetch();
    }

@Override
    public int countTickets(TnsTicketConfiguration ticketConfiguration) {
        return (int) this.buildQuery(ticketConfiguration).fetchCount();
    }

private JPAQuery buildQuery(TnsTicketConfiguration ticketConfiguration) {
        JPAQuery query = ticketQueryBuilder.prepareQuery();

        ticketQueryBuilder.setTicketIds(query, ticketConfiguration.getIds(), ticketConfiguration.isIncludeDoneTickets())
                .setStaffAndRolePermission(query, ticketConfiguration.getStaff(), ticketConfiguration.getStaffOrRolePermission())
                .setNotAssignedToEmployees(query, ticketConfiguration.getNotAssignedToEmployees())
                .setAllTechniciansWithoutSelf(query, ticketConfiguration.isAllTechnicians())
                .setCompanyIds(query, ticketConfiguration.getCompanies())
                .setDepartmentIds(query, ticketConfiguration.getDepartments())
                .setRemitterId(query, ticketConfiguration.getRemitterId())
                .setProjectId(query, ticketConfiguration.getProjectId())
                .setPhaseId(query, ticketConfiguration.getPhaseId())
                .setRepair(query, ticketConfiguration.getIsRepair())
                .setForProjectTickets(query, ticketConfiguration.getProjectFilter())
                .setNoProjectTickets(query, ticketConfiguration.isNoProjectTicket())
                .setLocalTicketAdminFilter(query, ticketConfiguration.getLocalTicketAdminFilter())
                .setRoleFilter(query, ticketConfiguration.getRoleFilter())
                .setCheckPermissionsOfUser(
                        query,
                        ticketConfiguration.isCheckPermissionsOfUser(),
                        ticketConfiguration.isHideLocalAdminTickets(),
                        ticketConfiguration.getExcludedTicketId()
                );

        return query;
    }
}

0 个答案:

没有答案