jeudi 19 juillet 2018

How do I mock an function from another package?

Somewhat of a golang beginner, but I've worked with testing frameworks before. How do I go about mocking out and faking what a dependent method returns without injecting the dependency? The reason why I don't want to use dependency injection is because there are many external package methods that are being used and injecting all of the methods in the constructor is unwieldy.

I've searched for this online/stackoverflow and solution is to always use dependency injection. Sometimes that is not a viable option.

Here's what I'm trying to do code-wise:

b/b_test.go

package b

func TestPrintResults(t *testing.T) {
    t.Run("Test", func(t *testing.T) {
        b := NewB()
        // How do I mock out and fake what a.DoSomething()
        // to be "complete" instead of whats in the code right now?
        result = b.Results
        assert.Equal(t, "complete", result)            
    }
}

b/b.go

package b

import (
    "a"
    "fmt"
)

type B struct {}

func NewB() B {
    return &B{}
}

func (b B) Results {
    return a.DoSomething()
}

a/a.go

package a
func DoSomething() {
    // Do something
    return "done"
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire