bytedance / mockey

a simple and easy-to-use golang mock library
Apache License 2.0
556 stars 22 forks source link

interface mocking #3

Open ZaynJarvis opened 1 year ago

ZaynJarvis commented 1 year ago

Is your feature request related to a problem? Please describe.

A quick guide for interface mocking is needed

Describe the solution you'd like

type Fooer interface{
    Foo(string) string
}

type A struct{}

func (a A) Foo(in string) string { return in }

func UseFoo(f Fooer) string {
        // something
        return f.Foo("")
}

func TestMockXXX(t *testing.T) {
    PatchConvey("TestMockXXX", t, func() {
                Mock(Fooer.Foo).Return("c").Build() // something like this is needed

        So(UseFoo(A{}), ShouldEqual, "c") // assert `Fooer.Foo` is mocked
    })
}

Describe alternatives you've considered

func TestMockXXX(t *testing.T) {
    PatchConvey("TestMockXXX", t, func() {
                MockInterface(Fooer.Foo).Return("c").Build() // something like this is needed

        So(UseFoo(A{}), ShouldEqual, "c") // assert `Fooer.Foo` is mocked
    })
}

Additional context

ycydsxy commented 1 year ago

Mock(Fooer.Foo).Return("c").Build() means 'mock every implements of the Fooer interface', right?

ZaynJarvis commented 1 year ago

yes that will be expected.

In case there are same interface in a structure for example

type A struct {
   X Fooer
   Y Fooer
}

Mock(A.X.Foo) may be a neat way.

DNSun commented 7 months ago

Is your feature request related to a problem? Please describe.

A quick guide for interface mocking is needed

Describe the solution you'd like

type Fooer interface{
  Foo(string) string
}

type A struct{}

func (a A) Foo(in string) string { return in }

func UseFoo(f Fooer) string {
        // something
        return f.Foo("")
}

func TestMockXXX(t *testing.T) {
  PatchConvey("TestMockXXX", t, func() {
                Mock(Fooer.Foo).Return("c").Build() // something like this is needed

      So(UseFoo(A{}), ShouldEqual, "c") // assert `Fooer.Foo` is mocked
  })
}

Describe alternatives you've considered

func TestMockXXX(t *testing.T) {
  PatchConvey("TestMockXXX", t, func() {
                MockInterface(Fooer.Foo).Return("c").Build() // something like this is needed

      So(UseFoo(A{}), ShouldEqual, "c") // assert `Fooer.Foo` is mocked
  })
}

Additional context

  • for now GetNestedMethod seems to work, but not elegant.
  • I know I can do interface insertion, but this Mock func is just so good, I want to use it the same way.

can't agree more! and how is the feature going? @ycydsxy

foundVanting commented 5 months ago

+1

stulzq commented 4 months ago

+1

zzraiyn1314 commented 2 weeks ago

+1

12345dotblue commented 2 weeks ago

+1