doubingjian2006 2014-08-27 10:14
浏览 23
已采纳

异常期间在golang中运行测试用例

I am writing testcases for method with doesnt return any values , for eg:

func GetByNameReturnNull(serName string)
{
 //Logic
}

My testcasefile is myTest.go which has two parameters , one calling the method with invalid input and calling the method with valid input.

func Test1(t *testing.T) { 
    GetByNameReturnNull("Invalid")
}


func Test2(t *testing.T) { 

    GetByNameReturnNull("valid")
}

So , the first testcase will fail and throw the exception , I cant handle it in the conventional way like ,

"check for err from the returned method because the method doesnt return anything at all. When I execute the command,

$go test ./... -v

the second testcase will not execute because of the exception of the first.

So Without changing any logic in the base method(GetByNameReturnNull) to return err or anything , is there any way to handle this scenario in the testcase file itself to print

1 fail 1 pass in the output?
  • 写回答

2条回答 默认 最新

  • dqba94394 2014-08-27 15:41
    关注

    @VonC is correct, there's no way to automatically handle it, however you can simply make a wrapper and call it in each test.

    This way you don't have to use a global variable to keep track of the tests.

    Example:

    func logPanic(t *testing.T, f func()) {
        defer func() {
            if err := recover(); err != nil {
                t.Errorf("paniced: %v", err)
            }
        }()
        f()
    }
    
    func Test1(t *testing.T) {
        logPanic(t, func() {
            GetByNameReturnNull("invalid")
        })
        //or if the function doesn't take arguments
        //logPanic(t, GetByNameReturnNull)
    }
    
    func Test2(t *testing.T) {
        logPanic(t, func() {
            GetByNameReturnNull("valid")
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)