func ValidateUserAuth(username, password, authUrl string) bool {
body, _ := json.Marshal(struct {
Username string
Password string
}{username,
password})
//调用外部接口
request, _ := http.NewRequest(http.MethodPost, authUrl, bytes.NewReader(body))
client := http.Client{}
response, _ := client.Do(request)
//如果返回的状态码为200则表示用户验证成功
return response.StatusCode == http.StatusOK
}
其中,authUrl参数为公司统一的权限校验接口,判断用户是否为公司员工。当然,这种参数传递方式可能不会出现在真正的代码中,没关系,我们先看这种方式,后面会优化为其他方式。
func TestValidateUserAuth(t *testing.T) {
//函数类型的变量,用户定义Web服务器行为
var handler http.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(200)
writer.Write(nil)
}
mockAuthServer := httptest.NewServer(handler)
success := ValidateUserAuth("user", "passwd", mockAuthServer.URL)
assert.True(t, success)
}
func GetAuthUrl() string {
//解析配置文件,返回对应的结构体
config := ParseConfig(configFilePath)
//返回配置文件中AuthUrl的值
return config.AuthUrl
}
我们定义了一个GetAuthUrl()方法用于获取第三方用户登陆服务的url。然后我们就可以将上面的权限验证代码稍作修改:
func ValidateUserAuth2(username, password string) bool {
//注意这行,我们通过调用GetAuthUrl()方法来获取第三方接口url
authUrl := GetAuthUrl()
body, _ := json.Marshal(struct {
Username string
Password string
}{username,
password})
request, _ := http.NewRequest(http.MethodPost, authUrl, bytes.NewReader(body))
client := http.Client{}
response, _ := client.Do(request)
return response.StatusCode == http.StatusOK
func TestValidateUserAuth2(t *testing.T) {
//函数类型的变量,用户定义Web服务器行为
var handler http.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(200)
writer.Write(nil)
}
mockAuthServer := httptest.NewServer(handler)
//1.对GetAuthUrl()方法进行打桩,返回mockAuthServer的url
patches := gomonkey.ApplyFunc(GetAuthUrl, func() string {
return mockAuthServer.URL
})
//2.在程序结束时恢复现场
defer patches.Reset()
success := ValidateUserAuth2("user", "passwd")
assert.True(t, success)
}
func TestApplyMethod(t *testing.T) {
slice := fake.NewSlice()
var s *fake.Slice
Convey("for succ", t, func() {
err := slice.Add(1)
So(err, ShouldEqual, nil)
//对方法打桩
patches := gomonkey.ApplyMethod(reflect.TypeOf(s), "Add", func(_ *fake.Slice, _ int) error {
return nil
})
defer patches.Reset()
err = slice.Add(1)
So(err, ShouldEqual, nil)
err = slice.Remove(1)
So(err, ShouldEqual, nil)
So(len(slice), ShouldEqual, 0)
})
}
var num = 1
func TestApplyGlobalVar(t *testing.T) {
patches := gomonkey.ApplyGlobalVar(&num, 100)
defer patches.Reset()
assert.Equal(t, num, 100)
}
4.数据库Mock
type Person struct {
Id int64
Name string
Age int
}
//向person表中插入一条记录
func InsertPerson(db *sql.DB, person *Person) (int64, error) {
sqlStr := "insert into person (name, age) values (?, ?)"
result, err := db.Exec(sqlStr, person.Name, person.Age)
if err != nil {
return -1, err
}
lastInsertId, _ := result.LastInsertId()
return lastInsertId, nil
}
//根据id查询对应的person记录
func QueryPersonById(db *sql.DB, id int64) (Person, error) {
sqlStr := "select name, age from person where id = ?"
result := Person{Id: id}
rows, err := db.Query(sqlStr, id)
if err != nil {
return result, err
}
if rows.Next(){
rows.Scan(&result.Name, &result.Age)
}
return result, nil
}
func TestInsertPerson(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectExec("insert into person").WillReturnResult(sqlmock.NewResult(100, 1))
p := &Person{
Name: "zhangsan",
Age: 23,
}
id, err := InsertPerson(db, p)
assert.Equal(t, id, int64(100))
assert.Nil(t, err)
}
func TestInsertPersonWithError(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectExec("insert into person").WillReturnError(errors.New("database internal error"))
p := &Person{
Name: "zhangsan",
Age: 23,
}
id, err := InsertPerson(db, p)
assert.Equal(t, id, int64(-1))
assert.NotNil(t, err)
}
func TestQueryPerson(t *testing.T) {
db, mock, _ := sqlmock.New()
//构造返回记录
rows := sqlmock.NewRows([]string{"name", "age"}).
AddRow("zhangsan", 23)
mock.ExpectQuery("select name, age from person").WillReturnRows(rows)
person, err := QueryPersonById(db, 1)
assert.Nil(t, err)
assert.Equal(t, person.Name, "zhangsan")
assert.Equal(t, person.Age, 23)
}
func TestSomething(t *testing.T) {
// All these assertions pass
assert.Equal(t, "hello", "hello", "Values are equal")
assert.NotEqual(t, "hello", "world", "Values are different")
assert.Contains(t, "hello", "el", "String contains other given string")
assert.True(t, true, "Value is true")
assert.False(t, false, "Value is false")
// All these assertions fail
assert.Equal(t, "hello", "world", "Values are equal")
assert.NotEqual(t, "hello", "hello", "Values are different")
assert.Contains(t, "hello", "y", "String contains other given string")
assert.True(t, false, "Value is true")
assert.False(t, true, "Value is false")
}
6.总结
文章来自一点资讯基础架构团队