Reputation: 520
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:
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)
Upvotes: 3
Views: 1295
Reputation: 520
Ended up making my structs 100% injectable, the code looks clear and concise and tests like a charm!
Upvotes: 1
Reputation: 327
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)
...
}
Upvotes: 2