Bài viết phổ biến của tác giả
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我很新。我正在尝试使用 testify
模拟 cấu trúc
的单个方法,但我不知道该怎么做。
Mã này như sau:
type HelloWorlder interface {
SayHello() string
GetName() string
}
type HelloWorld struct{}
func (hw *HelloWorld) SayHello() string {
return fmt.Sprintf("Hello World from %s!", hw.GetName())
}
func (hw *HelloWorld) GetName() string {
return "se7entyse7en"
}
这是测试:
type MockHelloWorld struct {
mock.Mock
HelloWorld
}
func (m *MockHelloWorld) GetName() string {
args := m.Called()
return args.String(0)
}
type SomeTestSuite struct {
suite.Suite
}
func (s *SomeTestSuite) TestMocking() {
mhw := new(MockHelloWorld)
mhw.On("GetName").Return("foo bar")
fmt.Println(mhw.SayHello())
}
想法是只模拟 GetName
方法,以便它打印 Hello World from foo bar!
。这可能吗?
对于那些熟悉 Python 的人来说,我要实现的目标与 unittest.Mock
类似。类允许通过 wraps
参数。
gia hạn从 testify
导入的包是这些:
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
câu trả lời hay nhất
也许这对你有帮助。
gói chính
nhập khẩu (
"fmt"
"github.com/stretchr/testify/mock"
)
type userReader interface {
ReadUserInfo(int) int
}
type userWriter interface {
WriteUserInfo(int)
}
type UserRepository struct {
userReader
userWriter
}
type realRW struct{}
func (db *realRW) ReadUserInfo(i int) int {
trở về tôi
}
func (db *realRW) WriteUserInfo(i int) {
fmt.Printf("put %d to db.\n", i)
}
// this is mocked struct for test writer.
type MyMockedWriter struct {
mock.Mock
}
func (m *MyMockedWriter) ReadUserInfo(i int) int {
args := m.Called(i)
return args.Int(0)
}
hàm main() {
rw := &realRW{}
repo := UserRepository{
userReader: rw,
userWriter: rw,
}
fmt.Println("Userinfo is:", repo.ReadUserInfo(100))
repo.WriteUserInfo(100)
// when you want to write test.
fmt.Println("Begin test....................")
testObj := new(MyMockedWriter)
testObj.On("ReadUserInfo", 123).Return(250)
testRepo := UserRepository{
userReader: testObj,
userWriter: rw,
}
fmt.Println("Userinfo is:", testRepo.ReadUserInfo(123))
testRepo.WriteUserInfo(100)
}
// Đầu ra:
// Userinfo is: 100
// put 100 to db.
// Begin test....................
// Userinfo is: 250
// put 100 to db.
祝你好运。
关于go - 作证模拟单一方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260189/
我在使用 testify 触发在 golang 中声明为变量的函数时遇到问题。 测试和函数都在同一个包中声明。 var testableFunction = func(abc string) stri
Tôi là một lập trình viên xuất sắc, rất giỏi!