Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add static validation of generated code for interface #67

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions mockgen/mockgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac
}

for _, intf := range pkg.Interfaces {
if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil {
if err := g.GenerateMockInterface(pkg.Name, intf, outputPackagePath); err != nil {
return err
}
}
Expand Down Expand Up @@ -431,7 +431,7 @@ func (g *generator) formattedTypeParams(it *model.Interface, pkgOverride string)
return long.String(), short.String()
}

func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error {
func (g *generator) GenerateMockInterface(pkgName string, intf *model.Interface, outputPackagePath string) error {
mockType := g.mockName(intf.Name)
longTp, shortTp := g.formattedTypeParams(intf, outputPackagePath)

Expand All @@ -445,6 +445,9 @@ func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePa
g.p("}")
g.p("")

// This adds validation in build time that mock type is still in sync with interface
g.p("var _ %v.%v = (*%v)(nil)", pkgName, intf.Name, mockType)

g.p("// %vMockRecorder is the mock recorder for %v.", mockType, mockType)
g.p("type %vMockRecorder%v struct {", mockType, longTp)
g.in()
Expand Down
2 changes: 1 addition & 1 deletion mockgen/mockgen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ func TestGenerateMockInterface_Helper(t *testing.T) {
intf.AddMethod(m)
}

if err := g.GenerateMockInterface(intf, "somepackage"); err != nil {
if err := g.GenerateMockInterface("packagename", intf, "somepackage"); err != nil {
t.Fatal(err)
}

Expand Down