3

I've been thinking about this whole night, but still cannot find an elegant way to do this thing. Let's say I have a struct

type file struct {
    x int
}

func (f *file) filename() string {
    return fmt.Sprintf("%s/%d.log", exportPath, f.x)
}

func (f *file) write(data []byte) {
    ...
    aFile = os.File.Open(f.filename())
    ...
}

Now I want to test write method and stub filename method to return temp filename. How can I do this? To the moment I found two options:

  1. declare filename = func(f* file) and override it in test
  2. make filename a field of the struct

But they both seem wrong in this case. So the question is - can I stub in any way this method? And in general - how to stub internal methods for testing (for external obviously dependency injection could work)

2 Answers 2

2

Making filename a field of the struct is an elegant way. The filename should be defined when new the struct.

type fileStruct {
    filename string
}

func newFileStruct(x int) *fileStruct {
    filename := fmt.Sprintf("%s/%d.log", exportPath, x)
    return &fileStruct{filename: filename}
}

func (f *fileStruct) write (data []byte) {
    ...
    file = os.File.Open(f.filename)
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Ended up making my structs 100% injectable, the code looks clear and concise and tests like a charm!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.