• go语言单元测试:go语言用gomonkey为测试函数或方法打桩


    一,安装用到的库
    1,gomonkey代码的地址:

    https://github.com/agiledragon/gomonkey

    2,从命令行安装gomonkey

    go get -u github.com/agiledragon/gomonkey
    3,goconvey库的代码地址

    https://github.com/smartystreets/goconvey

    4,从命令行安装

    go get -u github.com/smartystreets/goconvey

    二,演示项目的相关信息
    功能说明:演示了使用gomonkey库在项目中测试时打桩

    三,go代码说明
    1,model/user.go

    package model

    type MyUser struct {
    name string
    }

    //返回用户的name
    func (s *MyUser) GetUserName() string {
    return s.name
    }
    2,main.go

    package main

    //定义一个加法方法
    func Add(a, b int) int {
    return a + b
    }

    //定义方法,返回一个整数的2倍
    func GetDouble(a int) int {
    return Add(a,a)
    }
    3,main_test.go

    package main

    import (
    . "github.com/agiledragon/gomonkey"
    "github.com/liuhongdi/unittest03/model"
    . "github.com/smartystreets/goconvey/convey"
    "reflect"
    "testing"
    )



    //测试double,为add函数打桩1
    func TestDoubleRight(t *testing.T) {
    patch := ApplyFunc(Add, func(a,b int) int {
    return a * 2
    })
    defer patch.Reset()
    //fmt.Println(GetDouble(2))
    Convey("test 2 x 2", t, func() {
    So(GetDouble(2), ShouldEqual,4)
    })
    }

    //add函数的桩子
    func addstub(a,b int) int {
    return a*3
    }

    //测试double,为add函数打桩2
    func TestDoubleError(t *testing.T) {
    patch := ApplyFunc(Add, addstub)
    defer patch.Reset()
    //fmt.Println(GetDouble(2))
    Convey("test 2 x 2", t, func() {
    So(GetDouble(2), ShouldEqual,4)
    })
    }

    //测试给方法打桩1,返回正确
    func TestMethodRight(t *testing.T) {
    var temp *model.MyUser
    patch := ApplyMethod(reflect.TypeOf(temp), "GetUserName", func(_ *model.MyUser) string {
    return "hello,world!"
    })
    defer patch.Reset()
    Convey("GetUserName将返回:hello,world!", t, func() {
    var user *model.MyUser
    user = new(model.MyUser)
    So(user.GetUserName(), ShouldEqual, "hello,world!")
    })
    }

    //测试给方法打桩2,返回错误
    func TestMethodError(t *testing.T) {
    var temp *model.MyUser
    patch := ApplyMethod(reflect.TypeOf(temp), "GetUserName", func(_ *model.MyUser) string {
    return "hello,老刘!"
    })
    defer patch.Reset()
    Convey("GetUserName将返回:hello,world!", t, func() {
    var user *model.MyUser
    user = new(model.MyUser)
    So(user.GetUserName(), ShouldEqual, "hello,world!")
    })
    }
    四,测试效果
    执行测试:

    root@ku:/data/go/unittest03# go test -v ./... -gcflags "all=-N -l"
    注意:添加参数:-gcflags "all=-N -l"

    否则打桩可能不会生效

    返回:  

  • 相关阅读:
    Flink 架构和拓扑概览
    Flink 如何背压
    流式计算的时间模型
    流式计算的背压问题
    大数据流式计算容错方案演进之路
    Flink 任务提交
    Flink wordCount
    线性回归和逻辑回归的区别
    Nginx反向代理后配置404页面
    Httpclient 实现带参文件上传
  • 原文地址:https://www.cnblogs.com/gongxianjin/p/16361338.html
Copyright © 2020-2023  润新知