gostub

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2021 License: MIT Imports: 3 Imported by: 4

README

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.

Documentation

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.

Example (StubTimeWithConstant)

Test code

package main

import (
	"fmt"
	"time"

	"github.com/prashantv/gostub"
)

// Production code
var timeNow = time.Now

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

func main() {
	stubs := gostub.StubFunc(&timeNow, time.Date(2015, 07, 2, 0, 0, 0, 0, time.UTC))
	defer stubs.Reset()

	fmt.Println("Day:", GetDay())
}
Output:

Day: 2
Example (StubTimeWithFunction)

Test code

package main

import (
	"fmt"
	"time"

	"github.com/prashantv/gostub"
)

// Production code
var timeNow = time.Now

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

func main() {
	var day = 2
	stubs := gostub.Stub(&timeNow, func() time.Time {
		return time.Date(2015, 07, day, 0, 0, 0, 0, time.UTC)
	})
	defer stubs.Reset()

	firstDay := GetDay()

	day = 3
	secondDay := GetDay()

	fmt.Printf("First day: %v, second day: %v\n", firstDay, secondDay)
}
Output:

First day: 2, second day: 3

Index

Examples

Constants

View Source
const Version = "1.1.0"

Version contains the package version.

Variables

This section is empty.

Functions

func FuncReturning

func FuncReturning(funcType reflect.Type, results ...interface{}) reflect.Value

FuncReturning creates a new function with type funcType that returns results.

Types

type Stubs

type Stubs struct {
	// contains filtered or unexported fields
}

Stubs represents a set of stubbed variables that can be reset.

func New

func New() *Stubs

New returns Stubs that can be used to stub out variables.

func Stub

func Stub(varToStub interface{}, stubVal interface{}) *Stubs

Stub replaces the value stored at varToStub with stubVal. varToStub must be a pointer to the variable. stubVal should have a type that is assignable to the variable.

Example
package main

import (
	"fmt"

	"github.com/prashantv/gostub"
)

func main() {
	var counter = 100

	defer gostub.Stub(&counter, 200).Reset()
	fmt.Println("Counter:", counter)
}
Output:

Counter: 200

func StubFunc

func StubFunc(funcVarToStub interface{}, stubVal ...interface{}) *Stubs

StubFunc replaces a function variable with a function that returns stubVal. funcVarToStub must be a pointer to a function variable. If the function returns multiple values, then multiple values should be passed to stubFunc. The values must match be assignable to the return values' types.

Example
package main

import (
	"fmt"
	"os"

	"github.com/prashantv/gostub"
)

func main() {
	var osHostname = os.Hostname

	defer gostub.StubFunc(&osHostname, "fakehost", nil).Reset()
	host, err := osHostname()

	fmt.Println("Host:", host, "err:", err)
}
Output:

Host: fakehost err: <nil>

func (*Stubs) Reset

func (s *Stubs) Reset()

Reset resets all stubbed variables back to their original values.

func (*Stubs) ResetSingle

func (s *Stubs) ResetSingle(varToStub interface{})

ResetSingle resets a single stubbed variable back to its original value.

func (*Stubs) SetEnv

func (s *Stubs) SetEnv(k, v string) *Stubs

SetEnv the specified environent variable to the specified value.

func (*Stubs) Stub

func (s *Stubs) Stub(varToStub interface{}, stubVal interface{}) *Stubs

Stub replaces the value stored at varToStub with stubVal. varToStub must be a pointer to the variable. stubVal should have a type that is assignable to the variable.

func (*Stubs) StubFunc

func (s *Stubs) StubFunc(funcVarToStub interface{}, stubVal ...interface{}) *Stubs

StubFunc replaces a function variable with a function that returns stubVal. funcVarToStub must be a pointer to a function variable. If the function returns multiple values, then multiple values should be passed to stubFunc. The values must match be assignable to the return values' types.

func (*Stubs) UnsetEnv

func (s *Stubs) UnsetEnv(k string) *Stubs

UnsetEnv unsets the specified environent variable.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL