记录在使用Go进行web开发过程中的问题。
文章目录
<一>
1.由于GO本身没谁有数据库驱动,但留下了标准接口,所以使用第三方go-sql-driver/mysql驱动,使用过程如下:
import (
"database/sql"
_"github.com/go-sql-driver/mysql"
)
其中如果"github.com/go-sql-driver/mysql"不加空白符_会报错imported and not used: “github.com/go-sql-driver/mysql”。具体原因可参考博文:https://blog.csdn.net/westhod/article/details/80706836?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1。
2.在进行单元测试过程中需要满足:(1)测试文件必须和待测试文件在相同的文件夹下。(直接使用go test命令不加路径)(2)测试文件必须以Xxx_test.go命名。(3)测试文件中函数名称必须是TestXxx(t *testing.T)。
如:
package model
import (
"fmt"
"testing"
)
func TestAddusr(t *testing.T){
fmt.Println("测试")
usr := &Fortest{}
usr.Add()
}
若将TestAddusr(t *testing.T)改为testAddusr(t *testing.T),则无法自动测试,但可以作为一个子测试程序:
package model
import (
"fmt"
"testing"
)
func TestModel(t *testing.T) {
fmt.Print("测试Addusr方法")
t.Run("测试子程序:", testAddusr)
}
func testAddusr(t *testing.T){
fmt.Println("测试")
usr := &Fortest{}
usr.Add()
}
或
package model
import (
"fmt"
"testing"
)
func TestModel(t *testing.T) {
fmt.Print("测试Addusr方法")
testAddusr(t)
}
func testAddusr(t *testing.T){
fmt.Println("测试")
usr := &Fortest{}
usr.Add()
}
3.在测试函数执行之情如果需要先做其他操作使用如下方法:
func TestMain(m *testing.M) {
fmt.Print("先执行")
}
此时执行了TestMain,但没有执行测试函数,使用以下方法:
func TestMain(m *testing.M) {
fmt.Print("先执行")
m.Run()
}
这篇笔记记录了在Go语言进行Web开发时遇到的问题,包括如何使用go-sql-driver/mysql驱动(解决import错误),单元测试的规范(测试文件位置、命名及执行方式),以及在测试前执行预处理操作的方法。
537

被折叠的 条评论
为什么被折叠?



