【问题标题】:How to test native queries in Spring Boot application?如何在 Spring Boot 应用程序中测试本机查询?
【发布时间】:2019-07-13 04:16:18
【问题描述】:

我在遵循 TDD 方法的编码方面是全新的。现在,我不确定在编写每个代码之前是否需要测试用例。如何使用 if-else 条件测试本机查询?

我研究了以下一些方法,但没有满足我的问题:

Testing a Spring Boot application?

https://stackoverflow.com/search?q=test+entitymanager

https://stackoverflow.com/search?q=entitymanager+returned+null+in+testing

JUnit test if else case

@Transactional
public class ProfileRepositoryCustomImpl implements ProfileRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<ProfileMinimalResponseDTO> searchProfile(ProfileDTO profileDTO) {

        Query query = entityManager.createNativeQuery(QueryCreator.createQueryToSearchProfile.apply(profileDTO));

        List<Object[]> list = query.getResultList();

        if (ObjectUtils.isEmpty(list))
            throw new NoContentFoundException(NoRecordsFound.MESSAGE, NoRecordsFound.DEVELOPER_MESSAGE);

        return list.stream().map(
                ProfileUtils.convertObjectToProfileResponseDTO)
                .collect(Collectors.toList());
    }
}

实体看起来像:

@Entity
@Table(name = "profile")
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Profile implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "status")
    private Character status;

    @Column(name = "department_id")
    private Long departmentId;

    @Column(name = "sub_department_id")
    private Long subDepartmentId;

}

public class QueryCreator {

    public static Function<ProfileDTO, String> createQueryToSearchProfile = (profileDTO -> {
        String query = "";

        query += " SELECT" +
                " p.id," +                          //[0]
                " p.name," +                        //[1]
                " p.status," +                      //[2]
                " p.department_id," +               //[3]
                " p.sub_department_id" +            //[4]
                " FROM" +
                " profile p" +
                " WHERE p.id!=0";

        if (!Objects.isNull(profileDTO)) {
            if (!Objects.isNull(profileDTO.getName()))
                query += " AND p.name='" + profileDTO.getName() + "'";

            if (!Objects.isNull(profileDTO.getDepartmentId()))
                query += " AND p.department_id=" + profileDTO.getDepartmentId();

            if (!Objects.isNull(profileDTO.getSubDepartmentId()))
                query += " AND p.sub_department_id=" + profileDTO.getDepartmentId();
        }

        return query;
    });

}

 public static Function<Object[], ProfileMinimalResponseDTO> convertObjectToProfileResponseDTO = (objects) -> {

        final Integer ID = 0;
        final Integer NAME = 1;
        final Integer STATUS = 2;
        final Integer DEPARTMENT_ID = 3;
        final Integer SUB_DEPARTMENT_ID = 4;

        return ProfileMinimalResponseDTO.builder()
                .id(Long.parseLong(objects[ID].toString()))
                .name(objects[NAME].toString())
                .status(objects[STATUS].toString().charAt(0))
                .departmentId(Long.parseLong(objects[DEPARTMENT_ID].toString()))
                .subDepartmentId(Long.parseLong(objects[SUB_DEPARTMENT_ID].toString()))
                .build();
    };

我期待有关如何为上述场景编写测试用例的答案。此外,任何有关学习 TDD 的参考资料都会非常友好和有帮助。

【问题讨论】:

    标签: java unit-testing spring-boot tdd integration-testing


    【解决方案1】:

    关于学习 TDD 的参考资料,我绝对会推荐一本经典书籍,Kent Beck 的“TDD 示例”: https://www.amazon.co.uk/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530

    一种方法是使用一些内存数据库(H2 是 Spring Boot 的自然选择)。然后,您可以创建 schema.sqldata.sql 脚本来插入特定数据来测试您的极端情况。

    另一种选择是使用 Mockito 模拟 EntityManagerQuery 对象。然后,您无需使用插入和“创建表”创建 SQL,而是手动准备一组对象,这些对象将由这些模拟返回。

    希望这会有所帮助。如果您想让我详细说明一下,请告诉我。

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2023-03-10
      • 2016-04-05
      • 1970-01-01
      • 2022-01-13
      • 2018-03-20
      • 2021-05-27
      • 2017-01-30
      • 2016-07-01
      相关资源
      最近更新 更多