gostub is a library to make stubbing in unit tests easy

gostub

Build Status GoDoc Coverage Status

gostub is a library to make stubbing in unit tests easy.

Getting started

Import the following package: github.com/prashantv/gostub

Click here to read the API documentation.

Package overview

Package gostub is used for stubbing variables in tests, and resetting the original value once the test has been run.

This can be used to stub static variables as well as static functions. To stub a static variable, use the Stub function:

var configFile = "config.json"

func GetConfig() ([]byte, error) {
    return ioutil.ReadFile(configFile)
}

// Test code
stubs := gostub.Stub(&configFile, "/tmp/test.config")

data, err := GetConfig()
// data will now return contents of the /tmp/test.config file

gostub can also stub static functions in a test by using a variable to reference the static function, and using that local variable to call the static function:

var timeNow = time.Now

func GetDate() int {
    return timeNow().Day()
}

You can test this by using gostub to stub the timeNow variable:

stubs := gostub.Stub(&timeNow, func() time.Time {
    return time.Date(2015, 6, 1, 0, 0, 0, 0, time.UTC)
})
defer stubs.Reset()

// Test can check that GetDate returns 6

If you are stubbing a function to return a constant value like in the above test, you can use StubFunc instead:

stubs := gostub.StubFunc(&timeNow, time.Date(2015, 6, 1, 0, 0, 0, 0, time.UTC))
defer stubs.Reset()

StubFunc can also be used to stub functions that return multiple values:

var osHostname = osHostname
// [...] production code using osHostname to call it.

// Test code:
stubs := gostub.StubFunc(&osHostname, "fakehost", nil)
defer stubs.Reset()

StubEnv can be used to setup environment variables for tests, and the environment values are reset to their original values upon Reset:

stubs := gostub.New()
stubs.SetEnv("GOSTUB_VAR", "test_value")
defer stubs.Reset()

The Reset method should be deferred to run at the end of the test to reset all stubbed variables back to their original values.

You can set up multiple stubs by calling Stub again:

stubs := gostub.Stub(&v1, 1)
stubs.Stub(&v2, 2)
defer stubs.Reset()

For simple cases where you are only setting up simple stubs, you can condense the setup and cleanup into a single line:

defer gostub.Stub(&v1, 1).Stub(&v2, 2).Reset()

This sets up the stubs and then defers the Reset call.

You should keep the return argument from the Stub call if you need to change stubs or add more stubs during test execution:

stubs := gostub.Stub(&v1, 1)
defer stubs.Reset()

// Do some testing
stubs.Stub(&v1, 5)

// More testing
stubs.Stub(&b2, 6)

The Stub call must be passed a pointer to the variable that should be stubbed, and a value which can be assigned to the variable.

Owner
Similar Resources

Belajar golang unit test

perintah eksekusi di root folder : go test -v ./... assertion ambil dari framewo

Feb 3, 2022

Terratest is a Go library that makes it easier to write automated tests for your infrastructure code.

Terratest is a Go library that makes it easier to write automated tests for your infrastructure code. It provides a variety of helper functions and patterns for common infrastructure testing tasks,

Dec 30, 2022

A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Dec 19, 2021

Package for comparing Go values in tests

Package for equality of Go values This package is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two

Dec 29, 2022

Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Dec 22, 2022

Record and replay your HTTP interactions for fast, deterministic and accurate tests

go-vcr go-vcr simplifies testing by recording your HTTP interactions and replaying them in future runs in order to provide fast, deterministic and acc

Dec 25, 2022

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

GoConvey is awesome Go testing Welcome to GoConvey, a yummy Go testing tool for gophers. Works with go test. Use it in the terminal or browser accordi

Dec 30, 2022

Testing framework for Go. Allows writing self-documenting tests/specifications, and executes them concurrently and safely isolated. [UNMAINTAINED]

GoSpec GoSpec is a BDD-style testing framework for the Go programming language. It allows writing self-documenting tests/specs, and executes them in p

Nov 28, 2022

Ruby on Rails like test fixtures for Go. Write tests against a real database

testfixtures Warning: this package will wipe the database data before loading the fixtures! It is supposed to be used on a test database. Please, doub

Jan 8, 2023
Comments
  • Stub a func registered in some package's init()

    Stub a func registered in some package's init()

    hi I have a question here how to substitute a func in the init of some package. One example:

    package http func AuthenticationFilter(ctx context.Context) { .... } func init() { beego.InsertFilter("/", beego.BeforeExec, AuthenticationFilter) }

    I want to substitute AuthenticationFilter before the http package initialize. stubs.Stub(&http.AuthenticationFilter, func (ctx *context.Context) { ... }) How should I do? Thx a lot

  • download fail

    download fail

    1. go get -u -v github.com/prashantv/gostub then output is:

    ../../github.com/prashantv/gostub/env.go:7:15: error: reference to undefined identifier ¡®os.LookupEnv¡¯ v, ok := os.LookupEnv(k) ^ ../../github.com/prashantv/gostub/env.go:24:5: error: reference to undefined identifier ¡®os.Unsetenv¡¯ os.Unsetenv(k) ^ ../../github.com/prashantv/gostub/env.go:33:7: error: reference to undefined identifier ¡®os.Unsetenv¡¯ os.Unsetenv(k)

    what is wrong with it ?

    I can use "Stub" in my project , but when i use "go test", it shows error.

  • to extend APIs of gostub, to make it more powerful

    to extend APIs of gostub, to make it more powerful

    Hi, Prashant Varanasi! I am interested in gostub, offen use it to stub function variable. I added two APIs to gostub for supporting dynamic stubs, that is returning a different stub every time when the function is called mutiple times.

  • Fix StubFunc method

    Fix StubFunc method

    Hi Prashant! Hope you've been well!

    We came across an apparent bug in the Stubs.StubFunc method. Presumably, if this works:

    defer gostub.Stub(&v1, 1).Stub(&v2, 2).Reset()
    

    then this should too:

    defer gostub.StubFunc(&f1, 1).StubFunc(&f2, 2).Reset()
    

    However, as of now, this sort of thing behaves incorrectly. (Try running the test I added without the corresponding change in gostub.go.)

    Would it be possible to fix this? No rush at all; it's easy enough to work around.

How we can run unit tests in parallel mode with failpoint injection taking effect and without injection race

This is a simple demo to show how we can run unit tests in parallel mode with failpoint injection taking effect and without injection race. The basic

Oct 31, 2021
Rr-e2e-tests - Roadrunner end-to-end tests repository
Rr-e2e-tests - Roadrunner end-to-end tests repository

RoadRunner end-to-end plugins tests License: The MIT License (MIT). Please see L

Dec 15, 2022
go websocket client for unit testing of a websocket handler

wstest A websocket client for unit-testing a websocket server The gorilla organization provides full featured websocket implementation that the standa

Dec 21, 2022
Easier way to unit test terraform

Unit testing terraform (WIP) Disclaimer Currently, the only way to compare values is using JSON query path and all types are strings. want := terraf

Aug 16, 2022
A mock of Go's net package for unit/integration testing

netmock: Simulate Go network connections netmock is a Go package for simulating net connections, including delays and disconnects. This is work in pro

Oct 27, 2021
Go Unit Testing Clean Arch

Golang Unit Testing Tutorial melakukan unit testing di Golang yang sudah menerapkan clean architecture Menjalankan Service PSQL_HOST=<IP Database Serv

Feb 12, 2022
A simple yet intuitive golang unit test framework.

gotest Intuitive and simple golang testing framework which helps in writing unit tests in a way which improves the readability of the test. Here is an

Jan 1, 2022
Vault mock - Mock of Hashicorp Vault used for unit testing

vault_mock Mock of Hashicorp Vault used for unit testing Notice This is a person

Jan 19, 2022
Benchmarking deferent Fibonacci functions and algorithms with running unit test

GoFibonacciBench Benchmarking deferent Fibonacci functions and algorithms with running unit test ... Introduction: Fibonacci numbers are special kinds

Feb 27, 2022
This repository includes consumer driven contract test for provider, unit test and counter api.

This repository includes consumer driven contract test for provider, unit test and counter api.

Feb 1, 2022