登录
首页 >  Golang >  Go问答

前往 mockgen 以模拟未被调用的函数

来源:stackoverflow

时间:2024-02-28 15:54:25 156浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《前往 mockgen 以模拟未被调用的函数》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我在一台8核的windows机器上使用go 1.19,操作系统是windows 10 pro。 我使用mockgen工具来生成模拟。当我调试测试时,我看到执行 expect() 函数时记录了模拟方法。 模拟函数被调用,但测试失败,并出现模拟函数“缺少调用”。 我看不出我做错了什么,有人可以指出吗?

directory structure :
cmd
 configure.go
 configure_test.go
mocks
  mock_validator.go
validator
  validator.go
user
  user.go 
go.mod
main.go
* Contents of main.go
package main
import (
                "localdev/mockexample/cmd"
)
func main() {
                cmd.Configure()
}
* Contents of configure.go
package cmd
import (
                "fmt"
                "localdev/mockexample/user"
                "os"
                "localdev/mockexample/validator"
)
var (
                name, password string
)
func Configure() {
                name := os.Args[1]
                password := os.Args[2]
                user, err := validate(validator.NewValidator(name, password))
                if err != nil {
                                fmt.Printf("%v\n", err)
                                return
                }
                fmt.Printf("Credentials are valid. Welcome: %s %s\n", user.FirstName, user.LastName)
}
func validate(validator validator.Validator) (*user.Data, error) {
                user, err := validator.ValidateUser()
                if err != nil {
                                return nil, fmt.Errorf("some thing went wrong. %v", err)
                }
                return user, nil
}
* Contents of validator.go
package validator
import (
                "fmt"
                "localdev/mockexample/user"
)
//go:generate mockgen -destination=../mocks/mock_validator.go -package=mocks localdev/mockexample/validator Validator
type Validator interface {
                ValidateUser() (*user.Data, error)
}
type ValidationRequest struct {
                Command  string
                Name     string
                Password string
}
func (vr ValidationRequest) ValidateUser() (*user.Data, error) {
                if vr.Name == "bob" && vr.Password == "1234" {
                                return &user.Data{UserID: "123", UserName: "bsmith", FirstName: "Bob", LastName: "Smith"}, nil
                }
                return nil, fmt.Errorf("invalid credentials")
}
func NewValidator(name string, password string) Validator {
                return &ValidationRequest{Name: name, Password: password}
}
* Contents of user.go
package user
type Data struct {
                UserID    string `json:"user_id"`
                UserName  string `json:"user_name"`
                FirstName string `json:"first_name"`
                LastName  string `json:"last_name"`
}
* Contents of configure_test.go
package cmd
import (
                "localdev/mockexample/mocks"
                "localdev/mockexample/user"
                "os"
                "testing"
 
                "github.com/golang/mock/gomock"
)
func TestConfigure(t *testing.T) {
                t.Run("ConfigureWithMock", func(t *testing.T) {
                                os.Args[1] = "bob"
                                os.Args[2] = "1234"
 
                                ctrl := gomock.NewController(t)
                                mockValidator := mocks.NewMockValidator(ctrl)
                                //mockValidator.EXPECT().ValidateUser().AnyTimes() // zero more calls, so this will also pass.
                                userData := user.Data{UserID: "testId"}
                                mockValidator.EXPECT().ValidateUser().Return(&userData, nil).Times(1) //(gomock.Any(), gomock.Any()) //(&userData, nil)
                                Configure()
                })
}
Contents of generated mock
// Code generated by MockGen. DO NOT EDIT.
// Source: localdev/mockexample/validator (interfaces: Validator)
// Package mocks is a generated GoMock package.
package mocks
import (
                user "localdev/mockexample/user"
                reflect "reflect"
                gomock "github.com/golang/mock/gomock"
)
// MockValidator is a mock of Validator interface.
type MockValidator struct {
                ctrl     *gomock.Controller
                recorder *MockValidatorMockRecorder
}
// MockValidatorMockRecorder is the mock recorder for MockValidator.
type MockValidatorMockRecorder struct {
                mock *MockValidator
}
// NewMockValidator creates a new mock instance.
func NewMockValidator(ctrl *gomock.Controller) *MockValidator {
                mock := &MockValidator{ctrl: ctrl}
                mock.recorder = &MockValidatorMockRecorder{mock}
                return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockValidator) EXPECT() *MockValidatorMockRecorder {
                return m.recorder
}
// ValidateUser mocks base method.
func (m *MockValidator) ValidateUser() (*user.Data, error) {
                m.ctrl.T.Helper()
                ret := m.ctrl.Call(m, "ValidateUser")
                ret0, _ := ret[0].(*user.Data)
                ret1, _ := ret[1].(error)
                return ret0, ret1
}
// ValidateUser indicates an expected call of ValidateUser.
func (mr *MockValidatorMockRecorder) ValidateUser() *gomock.Call {
                mr.mock.ctrl.T.Helper()
                return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateUser", reflect.TypeOf((*MockValidator)(nil).ValidateUser))
}

正确答案


根本问题是函数 configure 从不使用模拟结构,因此您会收到 missing call(s) to *mocks.mockvalidator.validateuser() 错误。

在文件configure_test.go中,根本没有使用mockvalidator。必须对该模拟进行某种注入才能由 configure 函数调用。

您可以进行以下更改来修复测试,作为我提到的注入的示例。并不是说这是最好的方法,但我正在努力减少对代码的可能更改。

configure_test.go

func testconfigure(t *testing.t) {
    t.run("configurewithmock", func(t *testing.t) {
        os.args[1] = "bob"
        os.args[2] = "1234"

        ctrl := gomock.newcontroller(t)
        mockvalidator := mocks.newmockvalidator(ctrl)
        //mockvalidator.expect().validateuser().anytimes() // zero more calls, so this will also pass.
        userdata := user.data{userid: "testid"}
        mockvalidator.
            expect().
            validateuser("bob", "1234").
            return(&userdata, nil).
            times(1) //(gomock.any(), gomock.any()) //(&userdata, nil)
        configure(mockvalidator)
    })
}

configure.go

func configure(v validator.validator) {
    name := os.args[1]
    password := os.args[2]
    user, err := v.validateuser(name, password)
    if err != nil {
        fmt.printf("some thing went wrong. %v\n", err)
        return
    }
    fmt.printf("credentials are valid. welcome: %s %s\n", user.firstname, user.lastname)
}

validator.go

type Validator interface {
    ValidateUser(name, password string) (*user.Data, error)
}
type ValidationRequest struct {
    Command string
    // Name     string
    // Password string
}

func (vr ValidationRequest) ValidateUser(name, password string) (*user.Data, error) {
    if name == "bob" && password == "1234" {
        return &user.Data{UserID: "123", UserName: "bsmith", FirstName: "Bob", LastName: "Smith"}, nil
    }
    return nil, fmt.Errorf("invalid credentials")
}

func NewValidator() Validator {
    return &ValidationRequest{}
}

考虑到您需要再次生成模拟。希望这可以帮助您理解模拟测试。

好了,本文到此结束,带大家了解了《前往 mockgen 以模拟未被调用的函数》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>