简体   繁体   English

如何在Spring Boot应用程序中测试本地查询?

[英]How to test native queries in Spring Boot application?

I am completely new in coding by following TDD approach. 通过遵循TDD方法,我在编码方面是全新的。 Now, I'm not sure whether every code needs test case, before it is written. 现在,我不确定每个代码在编写之前是否都需要测试用例。 How do I test native queries with if-else conditions? 如何使用if-else条件测试本机查询?

I've researched some of the ways like following but didn't satisfy my question though: 我已经研究了以下一些方法,但并不能满足我的问题:

Testing a Spring Boot application? 测试Spring Boot应用程序?

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

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

JUnit test if else case JUnit测试其他情况

@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 looks like: 实体看起来像:

@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();
    };

I am expecting answers on how to write test case for above scenerio. 我期待有关如何为上述场景编写测试用例的答案。 Also, any references to learning TDD would be very kind and helpful. 此外,任何有关学习TDD的参考都将非常友善和有益。

regarding references for learning TDD I would definitely recommend a classic book, Kent Beck's "TDD by example": https://www.amazon.co.uk/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530 关于学习TDD的参考资料,我肯定会推荐一本经典的书,肯特·贝克(Kent Beck)的“ TDD以身作则”: https : //www.amazon.co.uk/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530

One approach would be to use some in-memory database (H2 being a natural choice in case of Spring Boot). 一种方法是使用一些内存数据库(在Spring Boot的情况下,自然选择H2)。 You could then create schema.sql and data.sql scripts to insert specific data to test your corner cases. 然后,您可以创建schema.sqldata.sql脚本插入特定的数据来测试您的极端情况。

Another option is to use Mockito to mock EntityManager and Query objects. 另一个选择是使用Mockito模拟EntityManagerQuery对象。 You then don't need to create SQL with inserts and 'create tables', but you prepare a set of objects manually which will be returned by these mocks. 然后,您不需要使用插入和“创建表”来创建SQL,但是您可以手动准备一组对象,这些对象将由这些模拟返回。

Hope this helps. 希望这可以帮助。 Let me know if you want me to elaborate on this a bit. 如果您想让我详细说明一下,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Boot + Hibernate Web 应用:如何全局拦截本机和托管实体查询? - Spring Boot + Hibernate Web Application: How to globally intercept native and managed entity queries? 如何在 Spring 引导应用程序中测试 @Configuration 和 @Bean? - How to test @Configuration and @Bean in a Spring Boot Application? 如何对 Spring Boot 应用程序进行集成测试? - How to do an integration test for a Spring Boot application? 如何在一次测试中启动2个春季启动应用程序? - How to boot up 2 spring boot application in one test? 如何在 Spring Boot 应用程序中启用 DynamoDB 查询日志记录? - How to enable logging of DynamoDB queries in the Spring Boot application? 当查询存储为外部文件时,如何在 Spring boot Repository 中为本机查询填充 @Query 值 - How to populate @Query value for native queries in Spring boot Repository when Queries are stored as external files 在 Spring Boot 应用程序中测试 websocket - Test websocket in spring boot application Cucumber 测试 Spring Boot 应用程序 - Cucumber Test a Spring Boot Application 春季启动测试启动应用程序 - Spring boot test starts Application 使用Arquillian测试Spring Boot应用程序 - Test Spring boot application with Arquillian
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM