You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
2.2 KiB
91 lines
2.2 KiB
2 months ago
|
package test
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"main/dao/mysql"
|
||
|
"main/logic"
|
||
|
"main/models"
|
||
|
"regexp"
|
||
|
"testing"
|
||
|
|
||
|
"github.com/DATA-DOG/go-sqlmock"
|
||
|
"github.com/jmoiron/sqlx"
|
||
|
"github.com/stretchr/testify/assert"
|
||
|
"github.com/stretchr/testify/require"
|
||
|
)
|
||
|
|
||
|
func TestGetAllStudentInfo(t *testing.T) {
|
||
|
// 创建一个模拟数据库
|
||
|
db, mock, err := sqlmock.New()
|
||
|
require.NoError(t, err)
|
||
|
defer db.Close()
|
||
|
|
||
|
sqlxDB := sqlx.NewDb(db, "mysql")
|
||
|
originalDB := mysql.GetDb()
|
||
|
mysql.ChangeDb(sqlxDB)
|
||
|
defer func() { mysql.ChangeDb(originalDB) }()
|
||
|
|
||
|
// 定义期望的查询和结果
|
||
|
rows := sqlmock.NewRows([]string{"user_id", "user_name", "user_gender", "user_score"}).
|
||
|
AddRow(1, "Alice", 1, 90).
|
||
|
AddRow(2, "Bob", 1, 85)
|
||
|
|
||
|
mock.ExpectQuery("(?i)SELECT user_id, user_name, user_gender, user_score FROM user ORDER BY user_score ASC").
|
||
|
WillReturnRows(rows)
|
||
|
|
||
|
// 调用被测试函数
|
||
|
result, err := mysql.GetAllStudentInfo() // 确保函数路径正确
|
||
|
require.NoError(t, err)
|
||
|
|
||
|
// 验证结果
|
||
|
expected := &[]models.User{
|
||
|
{User_id: 1, User_name: "Alice", User_gender: 1, User_score: 90},
|
||
|
{User_id: 2, User_name: "Bob", User_gender: 1, User_score: 85},
|
||
|
}
|
||
|
assert.Equal(t, expected, result)
|
||
|
|
||
|
// 验证所有期望的操作都已执行
|
||
|
err = mock.ExpectationsWereMet()
|
||
|
require.NoError(t, err)
|
||
|
}
|
||
|
|
||
|
func TestChangeStuScore(t *testing.T) {
|
||
|
db, mock, err := sqlmock.New()
|
||
|
require.NoError(t, err)
|
||
|
defer db.Close()
|
||
|
sqlxDB := sqlx.NewDb(db, "mysql")
|
||
|
originalDB := mysql.GetDb()
|
||
|
mysql.ChangeDb(sqlxDB)
|
||
|
defer func() { mysql.ChangeDb(originalDB) }()
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
}
|
||
|
sqlStr := `update user set
|
||
|
user_score = ?
|
||
|
where user_id=?`
|
||
|
mock.ExpectExec(regexp.QuoteMeta(sqlStr)).
|
||
|
WithArgs(95, 1).
|
||
|
WillReturnResult(sqlmock.NewResult(1, 1))
|
||
|
user := &models.UserScore{
|
||
|
User_id: 1,
|
||
|
User_score: 95,
|
||
|
}
|
||
|
err = mysql.ChangeStuScore(user)
|
||
|
require.NoError(t, err)
|
||
|
err = mock.ExpectationsWereMet()
|
||
|
require.NoError(t, err)
|
||
|
}
|
||
|
|
||
|
func TestWeightedRandomSelectWithMockRNG(t *testing.T) {
|
||
|
users := []models.User{
|
||
|
{User_id: 1, User_score: 0},
|
||
|
{User_id: 2, User_score: 10},
|
||
|
{User_id: 3, User_score: 20},
|
||
|
}
|
||
|
// 确定种子
|
||
|
rng := 42
|
||
|
expectedUser := users[0]
|
||
|
selectedUser := logic.WeightedRandomSelect(users, int64(rng))
|
||
|
require.Equal(t, expectedUser, selectedUser)
|
||
|
}
|