Skip to content

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

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.

Activity

  1. added
    ToolsThis label describes issues relating to any tools in the x/tools repository.
    goplsIssues related to the Go language server, gopls.
    on Jun 9, 2021
  2. added this to the Unreleased milestone on Jun 9, 2021
  3. findleyr commented on Jun 9, 2021

    @findleyr
    Contributor

    Thanks for the feature request. I agree that this could be a useful refactoring operation, and is certainly doable. It's also useful for more than just testing.

  4. added
    FeatureRequestIssues asking for a new feature that does not need a proposal.
    on Jun 9, 2021
  5. changed the title [-]x/tools/gopls: code action for extracting into interface[/-] [+]x/tools/gopls: code action to extracting an interface for usage[/+] on Feb 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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