【发布时间】: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
@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