gojuno/minimock

Simplify

Closed this issue · 3 comments

I use table tests and run each test inside a testing.T.Run closure and prefer to complete all test validation within the closure. To do this with minimock, I setup the mocks in my test cases with a nil minimock.Tester (NewXMock(nil)) and then within the closure, I do a type assertion on the mock, create a new controller, set the mock's tester and register the mock with the controller. Ex:

tests := []struct {
	name string
	x        X // an interface
	// additional test case details
}{
	{
		name: "testName",
		x:        NewXMock(nil),
		// additional test case setup
	},
}
for _, tt := range tests {
	tt := tt
	t.Run(tt.name, func(t *testing.T) {
		if m, ok := tt.x.(*XMock); ok {
			c := minimock.NewController(t)
			defer c.Finish()
			m.t = c
			c.RegisterMocker(m)
		}
		// perform test
	})
}

I would like to do something like:

c := minimock.NewController(t)
defer c.Finish()
c.AttachMock(tt.x)

Where AttachMock is defined like:

func (c Controller) AttachMock(m interface{}) {
	if m, ok := m.(interface{ SetTester(Tester) }); ok {
		m.SetTester(c)
	}
}

And generated mocks have:

func (m *XMock) SetTester(t minimock.Tester) {
	m.t = t

	if controller, ok := t.(minimock.MockController); ok {
		controller.RegisterMocker(m)
	}
}

Hi @sedalu

I understand your problem but I solve it differently, rather than defining mock as a property of table test I usually define mock as a property of tested entity (some struct for example) and I use closure that takes tester (minimock.Controller) and returns the tested entity. Minimock controller is created within the t.Run.

You can try look at this GoUnit template:
https://github.com/hexdigest/gounit/blob/master/templates/minimock

Or you can just follow the GoUnit readme and try to generate table test with minimock template to understand what's going on there.

I use gotest via VSCode, so I'll have to research how to use a custom template. But adding init func(t minimock.Tester, x *X) to the test case definition is an interesting idea.

@sedalu I believe that current version of gotest allows to use custom templates. I created GoUnit when gotest wasn't able to do this and generated pretty ugly test stubs.