How to mock "os" package function calls in a test case at go

I want to a test case for below code :

func WriteStringInFile(content string, fileName string) error {

	f, err := os.Create(fileName)
	defer f.Close()
	if err != nil {
		return err
	}
	_, err = f.WriteString(content)
	if err != nil {
		return err
	}
	return nil
}

I want to do something like this :

when(os.Create(fileName)).thenDoNothing()

Is there any good mocking framework in go, to mock those function calls?
or Can i do it without using any framework ?

You can use a variable to hold the function you want to replace at test time. For example, like below. That said, I don’t think I’ve ever wanted to replace os.Open. What is the scenario you’re testing for? I’d suggest trusting that os.Open works as advertised. If you want to do something like have it return an in memory buffer instead of a file so that you can inspect it for writes, it’s better to rearchitect your function to take an io.Writer and have the caller open the file. You can then pass a bytes.Buffer or similar during testing.

var osCreate = os.Create

func WriteStringInFile(content string, fileName string) error {
	f, err := osCreate(fileName)
	defer f.Close()
	if err != nil {
    ...

In your test code:

func TestBrokenOpen(t *testing.T) {
    osOpen = myBrokenOpen
    defer func() { osOpen = os.Open }()
    ...
}
2 Likes

For each call, I need to create a file and write strings into it.
but at time of running test case, i don’t want to create any run time resource like files.
Second thing, I could not create and read the file at the deployment environment.
otherwise, my test code is doing fine at local.

@calmh yes, you are correct, I can achieve this by memory buffer.
Thank you.

1 Like

You can also use virtual file system.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.