Mocking with Golang


Create the interface with one or more of the methods from the original package struct.

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.


E.g. This is 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)



Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s