完成分页查询参数的单元测试

pull/11/head^2
ZhouXY108 2025-01-01 20:37:21 +08:00
parent 6c225513ca
commit 25161044e9
5 changed files with 298 additions and 58 deletions

View File

@ -1,6 +1,6 @@
[ ] 未开始测试 - 0 (0.00%)
[*] 测试未完成 - 3 (04.84%)
[Y] 测试完成 - 37 (59.68%)
[*] 测试未完成 - 0 (0.00%)
[Y] 测试完成 - 40 (64.52%)
[-] 无需测试 - 22 (35.48%)
xyz.zhouxy.plusone.commons
@ -64,9 +64,9 @@ xyz.zhouxy.plusone.commons
│ │ ValidatableStringRecord.java [Y]
│ │
│ └───dto
│ PageResult.java [*]
│ PagingAndSortingQueryParams.java [*]
│ PagingParams.java [*]
│ PageResult.java [Y]
│ PagingAndSortingQueryParams.java [Y]
│ PagingParams.java [Y]
│ UnifiedResponse.java [Y]
├───time

14
pom.xml
View File

@ -82,6 +82,20 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.17</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
<scope>test</scope>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

View File

@ -16,88 +16,217 @@
package xyz.zhouxy.plusone.commons.model.dto.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxy.plusone.commons.model.dto.PageResult;
import xyz.zhouxy.plusone.commons.model.dto.PagingAndSortingQueryParams;
import xyz.zhouxy.plusone.commons.model.dto.PagingParams;
@Slf4j
public //
class PagingAndSortingQueryParamsTests {
public class PagingAndSortingQueryParamsTests {
static SqlSessionFactory sqlSessionFactory;
@BeforeAll
static void setUp() throws Exception {
initDatabase();
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
static void initDatabase() throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE;MODE=MySQL");
dataSource.setUser("sa");
dataSource.setPassword("");
List<AccountVO> data = Lists.newArrayList(
new AccountVO(1L, "zhouxy01", "zhouxy01@qq.com", 0, 108L, LocalDateTime.of(2020, 1, 1, 13, 15), 0L),
new AccountVO(2L, "zhouxy02", "zhouxy02@qq.com", 0, 108L, LocalDateTime.of(2020, 1, 2, 13, 15), 0L),
new AccountVO(3L, "zhouxy03", "zhouxy03@qq.com", 0, 108L, LocalDateTime.of(2020, 1, 3, 13, 15), 0L),
new AccountVO(4L, "zhouxy04", "zhouxy04@qq.com", 0, 108L, LocalDateTime.of(2020, 1, 4, 13, 15), 0L),
new AccountVO(5L, "zhouxy05", "zhouxy05@qq.com", 0, 108L, LocalDateTime.of(2020, 1, 5, 13, 15), 0L),
new AccountVO(6L, "zhouxy06", "zhouxy06@qq.com", 0, 108L, LocalDateTime.of(2024, 1, 6, 13, 15), 0L),
new AccountVO(7L, "zhouxy07", "zhouxy07@qq.com", 0, 108L, LocalDateTime.of(2024, 1, 7, 13, 15), 0L),
new AccountVO(8L, "zhouxy08", "zhouxy08@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 8, 13, 15), 0L),
new AccountVO(9L, "zhouxy09", "zhouxy09@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 9, 13, 15), 0L),
new AccountVO(10L, "zhouxy10", "zhouxy10@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 10, 13, 15), 0L),
new AccountVO(11L, "zhouxy11", "zhouxy11@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 11, 13, 15), 0L),
new AccountVO(12L, "zhouxy12", "zhouxy12@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 12, 13, 15), 0L),
new AccountVO(13L, "zhouxy13", "zhouxy13@qq.com", 1, 108L, LocalDateTime.of(2024, 5, 13, 13, 15), 0L),
new AccountVO(14L, "zhouxy14", "zhouxy14@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 14, 13, 15), 0L),
new AccountVO(15L, "zhouxy15", "zhouxy15@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 15, 13, 15), 0L),
new AccountVO(16L, "zhouxy16", "zhouxy16@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 16, 13, 15), 0L),
new AccountVO(17L, "zhouxy17", "zhouxy17@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 17, 13, 15), 0L),
new AccountVO(18L, "zhouxy18", "zhouxy18@qq.com", 1, 108L, LocalDateTime.of(2024, 10, 18, 13, 15), 0L),
new AccountVO(19L, "zhouxy19", "zhouxy19@qq.com", 1, 108L, LocalDateTime.of(2024, 11, 19, 13, 15), 0L),
new AccountVO(20L, "zhouxy20", "zhouxy20@qq.com", 1, 108L, LocalDateTime.of(2024, 12, 20, 13, 15), 0L)
);
try (Connection conn = dataSource.getConnection()) {
try (Statement statement = conn.createStatement()) {
String ddl = "CREATE TABLE sys_account ("
+ "\n" + " id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY"
+ "\n" + " ,username VARCHAR(255) NOT NULL"
+ "\n" + " ,email VARCHAR(255) NOT NULL"
+ "\n" + " ,status VARCHAR(2) NOT NULL"
+ "\n" + " ,create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP"
+ "\n" + " ,created_by BIGINT NOT NULL"
+ "\n" + " ,version BIGINT NOT NULL DEFAULT 0"
+ "\n" + ")";
statement.execute(ddl);
}
String sql = "INSERT INTO sys_account(id, username, email, status, create_time, created_by, version) VALUES"
+ "\n" + "(?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
for (AccountVO a : data) {
statement.setObject(1, a.getId());
statement.setObject(2, a.getUsername());
statement.setObject(3, a.getEmail());
statement.setObject(4, a.getStatus());
statement.setObject(5, a.getCreateTime());
statement.setObject(6, a.getCreatedBy());
statement.setObject(7, a.getVersion());
statement.addBatch();
}
statement.executeBatch();
statement.clearBatch();
}
}
}
static final String JSON_STR = "" +
"{\n" +
" \"size\": 15,\n" +
" \"pageNum\": 3,\n" +
" \"size\": 3,\n" +
" \"orderBy\": [\"username-asc\"],\n" +
" \"createTimeStart\": \"2024-05-06\",\n" +
" \"createTimeEnd\": \"2024-07-06\",\n" +
" \"updateTimeStart\": \"2024-08-06\",\n" +
" \"updateTimeEnd\": \"2024-10-06\",\n" +
" \"mobilePhone\": \"13169053215\"\n" +
" \"createTimeEnd\": \"2030-07-06\"" +
"}";
static final String WRONG_JSON_STR = "" +
"{\n" +
" \"pageNum\": 3,\n" +
" \"size\": 3,\n" +
" \"orderBy\": [\"status-asc\"],\n" +
" \"createTimeStart\": \"2024-05-06\",\n" +
" \"createTimeEnd\": \"2030-07-06\"" +
"}";
@Test
void testJackson() throws Exception {
try {
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
AccountQueryParams params = om.readValue(JSON_STR, AccountQueryParams.class);
log.info(params.toString());
ObjectMapper jackson = new ObjectMapper();
jackson.registerModule(new JavaTimeModule());
try (SqlSession session = sqlSessionFactory.openSession()) {
AccountQueryParams params = jackson.readValue(JSON_STR, AccountQueryParams.class);
PagingParams pagingParams = params.buildPagingParams();
log.info("pagingParams: {}", pagingParams);
AccountQueries accountQueries = session.getMapper(AccountQueries.class);
List<AccountVO> list = accountQueries.queryAccountList(params, pagingParams);
long count = accountQueries.countAccount(params);
PageResult<AccountVO> accountPageResult = PageResult.of(list, count);
log.info(jackson.writeValueAsString(accountPageResult));
assertEquals(Lists.newArrayList(
new AccountVO(14L, "zhouxy14", "zhouxy14@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 14, 13, 15), 0L),
new AccountVO(15L, "zhouxy15", "zhouxy15@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 15, 13, 15), 0L),
new AccountVO(16L, "zhouxy16", "zhouxy16@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 16, 13, 15), 0L)
), accountPageResult.getContent());
assertEquals(13, accountPageResult.getTotal());
} catch (Exception e) {
log.error("测试不通过", e);
throw e;
}
AccountQueryParams queryParams = jackson.readValue(WRONG_JSON_STR, AccountQueryParams.class);
assertThrows(IllegalArgumentException.class, () -> queryParams.buildPagingParams()); // NOSONAR
}
static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
static final TypeAdapter<LocalDate> dateAdapter = new TypeAdapter<LocalDate>() {
@Override
public void write(JsonWriter out, LocalDate value) throws IOException {
out.value(dateFormatter.format(value));
}
@Override
public LocalDate read(JsonReader in) throws IOException {
return LocalDate.parse(in.nextString(), dateFormatter);
}
};
@Test
void testGson() throws Exception {
try {
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, dateAdapter)
.create();
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {
@Override
public void write(JsonWriter out, LocalDate value) throws IOException {
out.value(dateFormatter.format(value));
}
@Override
public LocalDate read(JsonReader in) throws IOException {
return LocalDate.parse(in.nextString(), dateFormatter);
}
})
.create();
try (SqlSession session = sqlSessionFactory.openSession()) {
AccountQueryParams params = gson.fromJson(JSON_STR, AccountQueryParams.class);
log.info(params.toString());
PagingParams pagingParams = params.buildPagingParams();
log.info("pagingParams: {}", pagingParams);
AccountQueries accountQueries = session.getMapper(AccountQueries.class);
List<AccountVO> list = accountQueries.queryAccountList(params, pagingParams);
long count = accountQueries.countAccount(params);
PageResult<AccountVO> accountPageResult = PageResult.of(list, count);
log.info(gson.toJson(accountPageResult));
assertEquals(Lists.newArrayList(
new AccountVO(14L, "zhouxy14", "zhouxy14@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 14, 13, 15), 0L),
new AccountVO(15L, "zhouxy15", "zhouxy15@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 15, 13, 15), 0L),
new AccountVO(16L, "zhouxy16", "zhouxy16@qq.com", 1, 108L, LocalDateTime.of(2024, 8, 16, 13, 15), 0L)
), accountPageResult.getContent());
assertEquals(13, accountPageResult.getTotal());
} catch (Exception e) {
log.error("测试不通过", e);
throw e;
}
AccountQueryParams queryParams = gson.fromJson(WRONG_JSON_STR, AccountQueryParams.class);
assertThrows(IllegalArgumentException.class, () -> queryParams.buildPagingParams()); // NOSONAR
}
}
@ -113,15 +242,7 @@ class AccountQueryParams extends PagingAndSortingQueryParams {
private static final Map<String, String> PROPERTY_COLUMN_MAP = ImmutableMap.<String, String>builder()
.put("id", "id")
.put("username", "username")
.put("email", "email")
.put("mobilePhone", "mobile_phone")
.put("status", "status")
.put("nickname", "nickname")
.put("sex", "sex")
.put("createdBy", "created_by")
.put("createTime", "create_time")
.put("updatedBy", "updated_by")
.put("updateTime", "update_time")
.build();
public AccountQueryParams() {
@ -131,17 +252,10 @@ class AccountQueryParams extends PagingAndSortingQueryParams {
private @Getter @Setter Long id;
private @Getter @Setter String username;
private @Getter @Setter String email;
private @Getter @Setter String mobilePhone;
private @Getter @Setter Integer status;
private @Getter @Setter String nickname;
private @Getter @Setter Integer sex;
private @Getter @Setter Long createdBy;
private @Getter @Setter LocalDate createTimeStart;
private @Setter LocalDate createTimeEnd;
private @Getter @Setter Long updatedBy;
private @Getter @Setter LocalDate updateTimeStart;
private @Setter LocalDate updateTimeEnd;
private @Getter @Setter Long roleId;
public LocalDate getCreateTimeEnd() {
if (this.createTimeEnd == null) {
@ -149,11 +263,26 @@ class AccountQueryParams extends PagingAndSortingQueryParams {
}
return this.createTimeEnd.plusDays(1);
}
public LocalDate getUpdateTimeEnd() {
if (this.updateTimeEnd == null) {
return null;
}
return this.updateTimeEnd.plusDays(1);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
class AccountVO {
private Long id;
private String username;
private String email;
private Integer status;
private Long createdBy;
private LocalDateTime createTime;
private Long version;
}
interface AccountQueries {
List<AccountVO> queryAccountList(@Param("query") AccountQueryParams query,
@Param("page") PagingParams page);
long countAccount(@Param("query") AccountQueryParams query);
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE;MODE=MySQL"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="xyz/zhouxy/plusone/commons/model/dto/test/AccountQueries/AccountQueries.xml"/>
</mappers>
</configuration>

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xyz.zhouxy.plusone.commons.model.dto.test.AccountQueries">
<resultMap id="accountVO" type="xyz.zhouxy.plusone.commons.model.dto.test.AccountVO">
<id column="id" property="id" javaType="java.lang.Long" />
<result column="username" property="username" />
<result column="email" property="email" />
<result column="status" property="status" />
<result column="created_by" property="createdBy" />
<result column="create_time" property="createTime" />
<result column="version" property="version" />
</resultMap>
<select id="queryAccountList" resultMap="accountVO">
SELECT id, username, email, status, created_by, create_time, version
FROM sys_account a
<where>
<if test="query.id != null">
AND a.id = #{query.id}
</if>
<if test="query.username != null">
AND a.username = #{query.username}
</if>
<if test="query.email != null">
AND a.email = #{query.email}
</if>
<if test="query.status != null">
AND a.status = #{query.status}
</if>
<if test="query.createdBy != null">
AND a.created_by = #{query.createdBy}
</if>
<if test="query.createTimeStart != null">
AND a.create_time &gt;= #{query.createTimeStart}
</if>
<if test="query.createTimeEnd != null">
AND a.create_time &lt; #{query.createTimeEnd}
</if>
</where>
ORDER BY
<foreach collection="page.orderBy" index="i" item="property">
${property.sqlSnippet},
</foreach>
id ASC
LIMIT #{page.size} OFFSET #{page.offset}
</select>
<select id="countAccount">
SELECT count(*)
FROM sys_account a
<where>
<if test="query.id != null">
AND a.id = #{query.id}
</if>
<if test="query.username != null">
AND a.username = #{query.username}
</if>
<if test="query.email != null">
AND a.email = #{query.email}
</if>
<if test="query.status != null">
AND a.status = #{query.status}
</if>
<if test="query.createdBy != null">
AND a.created_by = #{query.createdBy}
</if>
<if test="query.createTimeStart != null">
AND a.create_time &gt;= #{query.createTimeStart}
</if>
<if test="query.createTimeEnd != null">
AND a.create_time &lt; #{query.createTimeEnd}
</if>
</where>
</select>
</mapper>