鉴于此代码
func doomed() {
  os.Exit(1)
}
如何正确测试调用此函数将导致存在使用go test?这需要在一组测试中发生,换句话说,os.Exit()调用不会影响其他测试并且应该被捕获.
说,我有以下代码打印一些日志消息.我如何测试是否记录了正确的消息?作为log.Fatal调用os.Exit(1),测试失败.
package main
import (
    "log"
)
func hello() {
    log.Print("Hello!")
}
func goodbye() {
    log.Fatal("Goodbye!")
}
func init() {
    log.SetFlags(0)
}
func main() {
    hello()
    goodbye()
}
以下是假设性测试:
package main
import (
    "bytes"
    "log"
    "testing"
)
func TestHello(t *testing.T) {
    var buf bytes.Buffer
    log.SetOutput(&buf)
    hello()
    wantMsg := "Hello!\n"
    msg := buf.String()
    if msg != wantMsg {
        t.Errorf("%#v, wanted %#v", msg, wantMsg)
    }
}
func TestGoodby(t *testing.T) {
    var buf bytes.Buffer
    log.SetOutput(&buf)
    goodbye()
    wantMsg := "Goodbye!\n" …我有以下测试方法,它使用从包导入的函数.
import x.y.z
func abc() {
    ...
    v := z.SomeFunc()
    ... 
}
是否有可能SomeFunc()在golang中嘲笑?
我正在使用Gin框架编写REST API.但我在测试我的控制器和研究TDD和Mock时遇到了麻烦.我尝试将TDD和Mock应用于我的代码,但我不能.
我创建了一个非常简化的测试环境,并尝试创建一个控制器测试.如何为Gin.Context创建模拟?
这是我的示例代码:
package main
import (
    "strconv"
    "github.com/gin-gonic/gin"
)
// MODELS
type Users []User
type User struct {
    Name string `json"name"`
}
func main() {
    r := gin.Default()
    r.GET("/users", GetUsers)
    r.GET("/users/:id", GetUser)
    r.Run(":8080")
}
// ROUTES
func GetUsers(c *gin.Context) {
    repo := UserRepository{}
    ctrl := UserController{}
    ctrl.GetAll(c, repo)
}
func GetUser(c *gin.Context) {
    repo := UserRepository{}
    ctrl := UserController{}
    ctrl.Get(c, repo)
}
// CONTROLLER
type UserController struct{}
func (ctrl UserController) GetAll(c *gin.Context, repository UserRepositoryIterface) {
    c.JSON(200, repository.GetAll())
} …假设我System.out.println(message)在所有地方打字都很无聊,我在java中介绍一个看起来像的方法
private void print (Object message) {
   System.out.println(message);
}
我会在必要的地方调用print (2)&print ("hi").
也可以在GoLang实现同样的目标吗?这样的功能
func print(message ) {
    fmt.Println (message)
}
由于外部库不公开接口(因此不是可模拟的),而仅公开纯函数,因此我很难在Go中编写单元测试。即使像Google这样的大公司也没有,所以我想知道我的方法是否足够好。库interface不是提供s而不是仅提供函数的包以便用户模拟它们的好习惯吗?
到目前为止,我想出的解决方案是将这些包与接口的实现包装在一起,但这似乎工作量太大。
我举一个例子。我的功能可能看起来像这样
func AnyFunction() error {
    sess := session.Get("blabla")
    // logic in here...
}
其中session是一个导入的包,返回struct。我不能嘲笑包裹session。对于这种情况,我将编写一个SessionInterface带有内部调用session的实现。
例如:
type SessionInterface interface {
    Get(s string) Session
}
type mySessionImpl struct {}
func (me *mySessionImpl) Get(s string) Session {
  return session.Get(s)
}
现在,为了进行测试,我可以模拟SessionInterface并将其注入我的代码中
什么时候在 Go 中使用 functioneExpression 而不是函数声明?
我搜索了 Function Expression vs Function Declaration(在 JS 中),它是关于提升的。高朗呢?