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条)

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题