Search code examples
gouuid

How to get different UUID each time a test is run in golang?


I've got an integration test that requires a different UUID each time its run but the following code generates the same uuid each time.

package service

import (
    "fmt"
    "testing"

    "github.com/google/uuid"
)

func TestOne(t *testing.T) {
    id, _ := uuid.NewRandom()
    fmt.Println(id)
}

Here is similar code in the Go Playground: https://play.golang.org/p/85yecbn4F80

How do I get this to return a new value with every execution?


Solution

  • Edit from June 21 2022: the scripts do not seem to be cached anymore when using https://go.dev/play/. A new UUID is printed on each run, even when the script remains the same.


    As users pointed out in the comments, the output in the Go playground is cached. If one tries this on their own command-line, a new UUID is printed on each run.

    package main
    
    import (
        "fmt"
    
        "github.com/google/uuid"
    )
    
    func main() {
        id, _ := uuid.NewRandom()
        fmt.Println(id)
    }
    

    And

    $ go run .
    604f5ea8-d146-4aac-9a15-4dc33a84eb59
    $ go run .
    3bc094cf-99c8-4250-98a0-9831fdadedac
    $ go run .
    b0c13db3-e466-4b5c-a179-e0a16469f11a
    

    For what it's worth, one can invalidate the Go playground cache by changing the script (e.g., add or modify a comment). This will cause a new UUID to be generated.