vendredi 18 janvier 2019

Go - Testify mocking a single method

I'm pretty new to go. I'm trying to mock a single method of a struct using testify, but I don't know how to do it.

Here's the code:

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

and here's the test:

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())
}

The idea is to mock only the GetName method so that it prints Hello World from foo bar!. Is that possible?

For those familiar with Python, what I'm trying to achieve is similar to what the unittest.Mock class permits through the wraps argument.

Aucun commentaire:

Enregistrer un commentaire