golang包的模拟方法

I have been unable to find a solution to mocking methods from golang packages.

For example, my project has code that attempts to recover when Os.Getwd() returns an error. The easiest way I can thinking of making a unit test for this, is by mocking the Os.Getwd() method to return an error, and verify that the code works accordingly.

I tried using testify, but it does not seem to be possible.

Anyone have any experience with that?

My own solution was to take the method as an argument, which allow to inject a "mock" instead when testing. Additionnaly, create an exported method as public facade and an unexported one for testing.

Example:

    func Foo() int {        
            return foo(os.Getpid)
    }                       

    func foo(getpid func() int) int {
            return getpid()      
    } 

Looks like that taking a look at the os.Getwd test could give you some example of how you could test your code. Look for the functions TestChdirAndGetwd and TestProgWideChdir.

From reading those, it seems that the tests create temporary folders.

So a pragmatic approach would be to create temporary folders, like the tests mentioned above do, then break them so os.Getwd throws an error for you to catch on your test.

Just be careful doing these operations as they can mess up your system. I'd suggest testing in a lightweight container or a virtual machine.

I know this is a bit late but, here is how you can do it.

Testing DAL or SystemCalls or package calls is usually difficult. My approach to solve this problem is to push your system function calls behind an interface and then mock the functions of those interface. For example.

type SystemCalls interface {
 Getwd() error
}


type SystemCallsImplementation struct{
}
func (SystemCallsImplementation) Getwd() error{
 return  Os.Getwd() 
}

func MyFunc(sysCall SystemCalls) error{

sysCall.Getwd()
}

With this you inject your interface that has the system calls to your function. Now you can easily create a mock implementation of your interface for testing.

like

type MockSystemCallsImplementation struct{
err error
}
func (MockSystemCallsImplementation) Getwd() error{
return err  //this can be set to nil or some value in your test function
}

Hope this answers your question.