Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not able to stub static function #16

Closed
rishavbhowmik opened this issue Sep 23, 2023 · 1 comment
Closed

Not able to stub static function #16

rishavbhowmik opened this issue Sep 23, 2023 · 1 comment

Comments

@rishavbhowmik
Copy link

rishavbhowmik commented Sep 23, 2023

Hi, I am new to GoLang, please pardon me in case this issue turns out to be lame.

Here is what I tried

import (
	"bytes"
	"testing"

	"github.com/prashantv/gostub"
)

// The function to stub
func RandomBytes(l uint8) ([]byte, error) {
	return []byte{1, 2, 3, 4}, nil
}

// The function to test
func PasswordHash(password string) ([]byte, error) {
	return RandomBytes(4)
}

// Test
func TestPasswordHash(t *testing.T) {
	var functionPtr = RandomBytes
	defer gostub.Stub(&functionPtr, func(l uint8) ([]byte, error) {
                println("Stub takes over") // This is never executed
		return []byte{5, 5, 5, 5}, nil
	}).Reset()

	hash, _ := PasswordHash("pass")
	if bytes.Compare(hash, []byte{5, 5, 5, 5}) != 0 {
		t.Error("Hash differs, stub didn't work. RandomSalt=", hash) // Test fails!
	}
}

So basically I am unable to stub the RandomBytes function.

Reproduced in playground

@prashantv
Copy link
Owner

gostub cannot stub static functions, it can only stub variables.

The typical usage is something like:

// Variable for stubbing
var randomBytesFunc = RandomBytes

func PasswordHash(password string) ([]byte, error) {
	// Use the variable for calling the function
	return randomBytesFunc(4)
}

And then gostub.Stub(&randomBytesFunc, ...) would replace the variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants