sách gpt4 ăn đã đi

go - 作证模拟单一方法

In lại 作者:数据小太阳 更新时间:2023-10-29 03:09:28 24 4
mua khóa gpt4 giày nike

我很新。我正在尝试使用 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ạntestify 导入的包是这些:

    "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/

24 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress