How to test a struct that calls its own method?


I have a struct:

type foo struct {
    bar mockableInterface // some interface that I can mock

func (f *foo) DoSmth1() []interface{} {

func (f *foo) DoSmth2() []interface{} {
    res := f.DoSmth1()
    //some code to test

Here I have no problem with mocking bar and testing DoSmth1(). But it’s not obvious how to test DoSmth2().
Should I rewrite this method to make it testable or rewrite tests somehow?


@mkopriva recommended just to mock Bar() call in DoSmth2() test. But in this case I would rewrite tests for all method that calls DoSmth1() every time it changes. So I’ve come to the following solution. We can encapsulate this mock logic in one method:

func (s *TestSuite) ExpectDoSmth1(times int, in, out []interface{}) {

This way we can change only this method if DoSmth1() implementation changes, till its API stays the same

Answered By – Russiancold

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.