Home > Backend Development > Golang > How Can I Mock Unmodifiable Go Code for Testing?

How Can I Mock Unmodifiable Go Code for Testing?

DDD
Release: 2024-12-09 17:31:17
Original
461 people have browsed it

How Can I Mock Unmodifiable Go Code for Testing?

Golang Monkey Patching for Unmodifiable Code

In Go, the absence of runtime object modification poses a challenge for testing heavily interconnected code that lacks dependency injection or interface programming. To work around this limitation, consider using the following approach:

Creating a Mocking Wrapper Interface

Define your own interface that wraps the original structs. For instance:

type MyInterface interface {
    DoSomething(i int) error
    DoSomethingElse() ([]int, error)
}
Copy after login

Using an Adapter Struct

Implement the wrapper interface in a new struct that adapts the original struct's implementation:

type Concrete struct {
    client *somepackage.Client
}

func (c *Concrete) DoSomething(i int) error {
    return c.client.DoSomething(i)
}

func (c *Concrete) DoSomethingElse() ([]int, error) {
    return c.client.DoSomethingElse()
}
Copy after login

Testing with the Wrapper

You can now mock the Concrete struct in unit tests because it adheres to an interface:

// Mock Concrete
mock := &MockMyInterface{}
c := Concrete{mock}

// Call mock method
err := c.DoSomething(10)
Copy after login

Embedding the Original Type

As suggested by @elithrar, you can also embed the original type to selectively mock only necessary methods:

type Concrete struct {
    *somepackage.Client
}
Copy after login

In this case, you can still access the original implementation of methods that don't need mocking:

c := Concrete{&somepackage.Client{}}
c.DoSomethingNotNeedingMocking() // Calls the original implementation
Copy after login

The above is the detailed content of How Can I Mock Unmodifiable Go Code for Testing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template