3-5.测试用例数据设定
约 406 字大约 1 分钟
2025-06-25
在测试用例中,避免使用固定的数据是至关重要的。 Spring Boot 提供了一种使用随机值的机制,通过在配置中生成随机数据,可以确保每次程序运行时加载的数据都是不同的。
1. YAML 配置中的随机值
可以在 application.yml
或 application.properties
配置文件中使用 Spring 的 SpEL (Spring Expression Language) 表达式来生成随机值。以下是一个示例:
testcase:
book:
id: ${random.int}
id2: ${random.int(10)}
type: ${random.int!5,10!}
name: ${random.value}
uuid: ${random.uuid}
publishTime: ${random.long}
以上配置将在每次程序启动时,为 testcase.book
下的各个属性生成随机值。
2. 使用 @ConfigurationProperties
加载随机数据
为了将这些随机数据加载到 Java 对象中,可以使用 @ConfigurationProperties
注解。首先,创建一个 Java 类,并使用 @Component
和 @Data
注解,然后使用 @ConfigurationProperties
指定配置的前缀。例如:
@Component
@Data
@ConfigurationProperties(prefix = "testcase.book")
public class BookCase {
private int id;
private int id2;
private int type;
private String name;
private String uuid;
private long publishTime;
}
在这个例子中,BookCase
类的属性会自动绑定到 testcase.book
前缀下的配置属性。
3. 随机值限定规则
Spring 提供了多种生成随机值的 SpEL 表达式,并且可以对生成的数值进行范围限定:
${random.int}
:生成一个随机整数。${random.int(10)}
:生成一个 0 到 9 之间的随机整数。${random.int(10,20)}
:生成一个 10 到 20 之间的随机整数。
在 ${random.int(10,20)}
中,可以使用任意字符作为分隔符,例如 !
或 []
,${random.int!10,20!}
与 ${random.int[10,20]}
都是有效的。