1

I'm writing some unit tests, and I'm stuck writing a test for the following method:

func (database *Database) FindUnusedKey() string {
    count := 0
    possibleKey := helpers.RandomString(helpers.Config.KeySize)
    for database.DoesKeyExist(possibleKey) {
        possibleKey = helpers.RandomString(helpers.Config.KeySize + uint8(count/10))
        count++
    }
    return possibleKey
}

I want a test in which helpers.RandomString(int) returns a string that is already a key in my database, but I've found no way to redeclare or monkey patch helpers.RandomString(int) in my test.

I tried using testify mock, but it doesn't seem possible.

Am I doing something wrong?

Thanks.

icza
  • 389,944
  • 63
  • 907
  • 827
Gregorio Di Stefano
  • 1,173
  • 1
  • 15
  • 23
  • You don't mention the DB engine youre using, but most relational databases do have means to generate keys (sequence, auto inc fields). I would suggest to use these instead of generating keys at client side. – ain Jul 02 '16 at 11:12
  • I have not used it myself, but it seems to have autoinc for keys: https://github.com/boltdb/bolt#autoincrementing-integer-for-the-bucket – ain Jul 02 '16 at 11:35

1 Answers1

0

You can extract database.DoesKeyExist via dependency injection and supply a function that returns true first time in unit tests. More details http://openmymind.net/Dependency-Injection-In-Go/