Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock a function from another package without using dependency injection?

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 the 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 TestResults(t *testing.T) {
    t.Run("Test", func(t *testing.T) {
        b := NewB()
        // How do I mock out and fake 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"

type B struct {}

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

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

a/a.go

package a

func DoSomething() {
    return "done"
}

Thanks!

like image 272
perseverance Avatar asked Jul 19 '18 17:07

perseverance


People also ask

Is mocking a dependency injection?

Dependency injection is a way to scale the mocking approach. If a lot of use cases are relying on the interaction you'd like to mock, then it makes sense to invest in dependency injection. Systems that lend themselves easily to dependency injection: An authentication/authorization service.

How do you mock an external function in jest?

To change the mock implementation of a function with Jest we use the mockImplementation() method of the mocked function. The mockImplementation() method is called with the new implementation as its argument. The new implementation will then be used in place of the previous one when the mock is called.

What is auto mocking jest?

Jest offers many features out of the box. One that is very powerful and commonly used in unit tests is the auto mock feature, which is when Jest automatically mocks everything exported by a module that is imported as a dependency by any module we are testing.


Video Answer


1 Answers

You can use conditional compilation with build tags

a/a.go

// +build !mock

package a
func DoSomething() {
    return "done"
}

a/a_mock.go

// +build mock

package a
func DoSomething() {  // Insert fake implementation here
    return "complete"
}

$ go test -tags mock

like image 156
Uvelichitel Avatar answered Sep 28 '22 08:09

Uvelichitel