java 使用pageRequest测试Spring存储库

bqjvbblv  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(164)

我有存储库:

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findAllByPriceBetween(BigDecimal from, BigDecimal to, PageRequest pageRequest);
}

在liquibase我只是创建表:

--liquibase formatted sql
--changeset <sniklz>:<create-products-table>
CREATE TABLE IF NOT EXISTS products
(
    id bigint auto_increment,
    title varchar(255) not null,
    price decimal      not null,
    CONSTRAINT product_pl PRIMARY KEY (id)
);

--rollback DROP TABLE products;

然后我尝试测试我的存储库:

@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase (replace = AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest  {
    @Container
    static MySQLContainer<?> database = new MySQLContainer<>("mysql:8")
            .withDatabaseName("springboot")
            .withPassword("springboot")
            .withUsername("springboot");

    @DynamicPropertySource
    static void setDataSourceProperties(DynamicPropertyRegistry propertyRegistry) {
        propertyRegistry.add("spring.datasource.url", database::getJdbcUrl);
        propertyRegistry.add("spring.datasource.username", database::getUsername);
        propertyRegistry.add("spring.datasource.password", database::getPassword);
    }

    @Autowired
    private ProductRepository productRepository;

    @Test
    @Sql("/scripts/init_four_products.sql")
    void shouldReturnProductPriceGreaterThan1200() {
        List<Sort.Order> order = new ArrayList<>();
        order.add(new Sort.Order(Sort.Direction.DESC, "price"));
        Sort sort = Sort.by(order);
        PageRequest pageRequest = PageRequest.of(0, 10, sort);
        List<Product> acutal = productRepository.findAllByPriceBetween(BigDecimal.valueOf(1200),
                BigDecimal.valueOf(Integer.MAX_VALUE), pageRequest);
        Assertions.assertEquals(1, acutal.size());
        Assertions.assertEquals("iPhone XI", acutal.get(0).getTitle());
    }
}

在/scripts/init_four_products. sql中,我只创建一些产品:

INSERT INTO products (title, price) VALUES ("iPhone 8", 700);
INSERT INTO products (title, price) VALUES ("iPhone 9 ", 800);
INSERT INTO products (title, price) VALUES ("iPhone X", 1000);
INSERT INTO products (title, price) VALUES ("iPhone XI", 1200);

但有错误:
数据访问无效应用程序使用异常:至少提供了3个参数,但查询中仅存在2个参数。嵌套异常是java. lang.至少提供了3个参数,但查询中仅存在2个参数。
我没有找到任何有用的信息在谷歌

wn9m85ua

wn9m85ua1#

根据Spring文档:
基础结构识别某些特定的类型,如PageableSort,以便动态地对查询应用分页和排序。
也就是说,您应该在ProductRepository方法中将PageRequest替换为Pageable

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findAllByPriceBetween(BigDecimal from, BigDecimal to, Pageable pageable);
}

Pageable应按如下方式示例化:

Pageable pageable = PageRequest.of(0, 10, sort);

相关问题