Mocking with Golang
Overview
Writing unit tests are vital and ensures the integrity of your code. But sometimes it is hard to write tests for code that references external dependencies. That is where Go makes mocking such services easy.
The core idea is to create the interface with one or more of the methods from the original package struct.
For example, I wrote a wrapper SFTP package to create SFTP connections and download/upload files.
Inorder to test this package, rather than downloading and uploading files to an actual SFTP server, I used mocking so it would still test the flow of the package.
Implementation
First define an interface so we can mock the sftphelper.SFTPConnection struct:
type SftpConnector interface { RemoveFile(string) error }
Write the mock struct using the interface
type FakeSftpConnector struct { } // make sure it satisfies the interface var _ SftpConnector = (*FakeSftpConnector)(nil) func (f *FakeSftpConnector) RemoveFile(source string) error { ... }
Update your function that takes the sftphelper.SFTPConnection struct function to take the new interface instead
In your test code, you can send in the fake struct instead and make assertions on the inputs after calling the target function
func TestProcessInnerFiles(t *testing.T) { tt := &FakeSftpConnector{} err := processInnerFiles(tt, "/home/ftptest/feed_20160912/", "IN7994_20160715.json") if err != nil { t.Errorf("Error was not expected in processInnerFiles: %s", err) } }