Skip to content

x/tools/gopls: code action to extracting an interface for usage #46665

Open
@js-sketch

Description

@js-sketch

Consider the following program:

type bar struct {}
func (b *bar) x() {}
func (b *bar) y() {}
type Foo struct {
    bar *bar
}
func (f *Foo) baz() {
    f.b.y()
}

Now assume we would like to test foo and for this we'd want to mock bar. The recommended way of doing this is to extract the way that bar is used into an interface and use that in lieu of bar in foo.

type bar struct {}
func (b *bar) x() {}
func (b *bar) y() {}

type barI interface {
    y()
}
type Foo struct {
    bar barI
}
func (f *Foo) baz() {
    f.b.y()
}

Note that only y() was extracted.
Supporting such a code action in gopls would make life a lot easier for devs who write unit tests.
This is at least viable to implement for unexported members, as no new methods can be added in other packages which access this member.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.RefactoringIssues related to refactoring toolsToolsThis label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions