'How to mock *exec.Cmd / exec.Command()?

I need to mock exec.Command().

I can mock it using:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return nil
}

However, this won't work in the actual code, as it complains about the nil pointer, since the returning exec.Cmd calls Run().

I tried to mock it like:

type mock exec.Cmd

func (m *mock) Run() error {
    return nil
}

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    m := mock{}

    return &m
}

But it complains: cannot use &m (value of type *mock) as *exec.Cmd value in return statementcompilerIncompatibleAssign.

Is there any way to approach this? Is there a better way to mock exec.Command()?

The mocked function works if I return a "mock" command, although I'd prefer to control the Run() function too:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return exec.Command("echo")
}


Solution 1:[1]

How to mock *exec.Cmd / exec.Command()?

You cannot. Come up with a non mock-based testing strategy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Volker