假设我们要测试一个简单的班级管理系统,其中包括学生的姓名、年龄、成绩三个属性。下面是一个简单的学生信息增删改查的操作示例:
首先,我们需要先初始化班级和学生的信息:
# 初始化班级信息
init_classroom() {
curl -X POST -d '{"name":"class1"}' http://localhost:8080/classroom
}
# 初始化学生信息
init_student() {
for i in {
1..3}; do
echo "{\"name\":\"student${i}\",\"age\":$((i+10)),\"score\":$((i*50))}" | \
curl -X POST -H "Content-Type: application/json" -d @- http://localhost:8080/student
done
}
接下来,我们可以写几个简单的测试用例:
- 创建一个新班级:
test_add_classroom() { local classroom_id=$(curl -X POST -d "{\"name\":\"class2\"}" http://localhost:8080/classroom | jq -r '.id') assertEquals "class2" "$(curl -X GET "http://localhost:8080/classroom/${classroom_id}/info" | jq -r '.name')" }
- 删除一个班级:
test_remove_classroom() { local classroom_id=$(curl -X POST -d "{\"name\":\"class3\"}" http://localhost:8080/classroom | jq -r '.id') assertEquals "200" "$(curl -X DELETE "http://localhost:8080/classroom/${classroom_id}" | jq -r '.code')" }
更新一个班级:
test_update_classroom() { local classroom_id=$(curl -X POST -d "{\"name\":\"class4\"}" http://localhost:8080/classroom | jq -r '.id') assertEquals "200" "$(curl -X PUT -d "{ \"name\":\"new_name\"}" "http://localhost:8080/classroom/${classroom_id}" | jq -r '.code')" assertEquals "new_name" "$(curl -X GET "http://localhost:8080/classroom/${classroom_id}/info" | jq -r '.name')" }
- 查询学生信息:
test_query_students() { local student_ids=$(curl -X GET "http://localhost:8080/students" | jq -r '.[] | .id') for student_id in $student_ids; do assertEquals "student$i" "$(curl -X GET "http://localhost:8080/student/${student_id}/info" | jq -r '.name')" done }
- 添加一个学生:
test_add_student() { local student_id=$(curl -X POST -d "{\"name\":\"student4\",\"age\":40,\"score\":200}" http://localhost:8080/student | jq -r '.id') assertEquals "200" "$(curl -X GET "http://localhost:8080/student/${student_id}/info" | jq -r '.code')" assertEquals "student4" "$(curl -X GET "http://localhost:8080/student/${student_id}/info" | jq -r '.name')" }
修改一个学生:
test_update_student() { local student_id=$(curl -X POST -d "{\"name\":\"student5\",\"age\":50,\"score\":250}" http://localhost:8080/student | jq -r '.id') assertEquals "200" "$(curl -X PUT -d "{ \"name\":\"new_name\"}" "http://localhost:8080/student/${student_id}" | jq -r '.code')" assertEquals "new_name" "$(curl -X GET "http://localhost:8080/student/${student_id}/info" | jq -r '.name')" }
- 删除一个学生:
test_remove_student() { local student_id=$(curl -X POST -d "{\"name\":\"student6\",\"age\":60,\"score\":300}" http://localhost:8080/student | jq -r '.id') assertEquals "200" "$(curl -X DELETE "http://localhost:8080/student/${student_id}" | jq -r '.code')" }
最后,我们可以定义一个函数来运行所有的测试用例:
run_test() {
init_classroom
init_student
test_add_classroom
test_remove_classroom
test_update_classroom
test_query_students
test_add_student
test_update_