[英]How to mock function in go?
package main
import (
"net/http"
"sync"
"time"
)
type SessionInterface1 interface {
doLoginAndReadDestinations1() bool
}
type Session1 struct {
sessionCookie string
mux sync.Mutex
sessionTime time.Time
targetAddress string
currentJwt string
transport *http.Transport
}
var currentSession1 Session1
func main() {
currentSession1.verifyLogin1()
}
func (s *Session1) doLoginAndReadDestinations1() bool {
..logic...
... for example return true
}
func callDest1(si SessionInterface1) bool {
return si.doLoginAndReadDestinations1()
}
func (s *Session1) verifyLogin1() bool {
return callDest1(s)
}
我想创建单元测试并模拟doLoginAndReadDestinations1,我尝试为此方法创建接口并创建测试
func test1(t *testing.T) {
type args struct {
}
tests := []struct {
name string
args args
want bool
}{{
name: "test",
args: args{},
want: false,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var s1 *Session1
count := 10
s1 = &Session1{"", sync.Mutex{}, time.Now(), "", "", nil}
var got1 = s1.verifyLogin()
if got1 != tt.want {
t.Errorf("getJwt() = %v, want %v", got, tt.want)
}
})
}
}
我不知道如何在测试中更改函数doLoginAndReadDestinations1的逻辑并在第一个main中更改逻辑
在单元测试中,您仅在Session1
上调用方法,而不在调用 Session1
的方法上调用 ; 所以没有什么可嘲笑的。 当使用模拟进行测试时,您不会模拟方法 ,也不会模拟类型 ,只要这些类型是被测试类型的依赖项即可。 例如,如果您有一个Foo
类型依赖于Bar
类型(调用方法),并且想要Foo
测试Foo
,则可以创建Bar
类型的模型,并在对Foo
的测试中给出它是您的BarMock
而不是Bar
。 在您的真实代码中,您将为其赋予真实的Bar
。 无法模拟一种类型的单个方法。
您可能会发现此StackOverflow问题及其广泛的答案很有帮助。
您将需要抽象所有想要模拟的东西。 不要将依赖关系作为具体的实现来解决,而要使用接口。 然后,您将能够创建将实现此接口的模拟。
通常,我建议您使用担架/作证进行测试。 它具有以下方法:
该库将帮助您构建测试,编写测试并删除样板代码。 它内部具有嘲讽机制 。 在testify模拟部分阅读有关模拟接口的信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.