Wednesday 9 April 2014

Simple and Quick way to stub a method

Simple and Quick way to stub a method

Go having functions as first class citizens enables you to override the implementation of a function.  I have just used it to enable me to test a method quickly. (I know I could have abstracted the code out and tested the separate function, but really wanted to give this a go)

So creating a new variable and setting it to be a function is really easy.

var calculate = func (a, b int) int {

     return a + b
}

You can use this variable just like you are calling a function


c := calculate(1 + 2)


Now lets say you want to get a different result in a test. Well you can override the functional implementation.

calculate = func(a, b int) int {

    return 20
}

This now means when this function is called in your code it will return 20 every time, no matter what you pass in. However in your real code, it will run your function you declared in the real code.

This is a simple example. However it could be a quick and easy way of mocking data access layer requests for tests without setting up a mocking framework.

How it helps