捕获传递给函数的参数

huangapple go评论81阅读模式
英文:

Capture argument passed to a function

问题

在单元测试中,我已经为函数ExecuteDeleteQuery创建了一个模拟对象。

ExecuteDeleteQuery = func(deleteQuery string) ([]string, error) {
    return nil, nil
}

我该如何捕获传递给这个函数的参数并进行断言呢?我想要做类似这样的操作:

assertEqual(t, deleteQuery, expectedDeleteQuery)
英文:

In a unit test, I have created mock for the function ExecuteDeleteQuery

ExecuteDeleteQuery = func(deleteQuery string) ([]string, error) {
	return nil,nil
}

How can I capture the argument passed to this function and assert that?
I want to do something like:

assertEqual(t, deleteQuery, expectedDeleteQuery)

答案1

得分: 3

如果你只需要捕获一个值,你可以这样做:

var gotDeleteQuery string

ExecuteDeleteQuery = func(deleteQuery string) ([]string, error) {
    gotDeleteQuery = deleteQuery
    return nil, nil
}

// ...

assertEqual(t, gotDeleteQuery, expectedDeleteQuery)

这段代码的作用是将 deleteQuery 的值赋给 gotDeleteQuery,然后通过 assertEqual 函数来断言 gotDeleteQuery 是否等于 expectedDeleteQuery

英文:

If you just need to capture one value, you can do something like this:

var gotDeleteQuery string

ExecuteDeleteQuery = func(deleteQuery string) ([]string, error) {
	gotDeleteQuery = deleteQuery
    return nil,nil
}

// ...

	assertEqual(t, gotDeleteQuery, expectedDeleteQuery)

huangapple
  • 本文由 发表于 2022年5月28日 22:01:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/72416274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定