Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I check in my test that the method returns a time.ticker with the specified duration?

How can I test for the correct return value in this method?

func CreateTicker(dur time.Duration) *time.Ticker {
    return time.NewTicker(dur * time.Second)
}
func TestCreateTicker(t *testing.T) {
    type args struct {
        dur time.Duration
    }
    var (
        ticker = time.NewTicker(12)
    )

    tests := []struct {
        name string
        args args
        want *time.Ticker
    }{
        {
            name: "test",
            args: args{dur: 12},
            want: ticker,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := CreateTicker(tt.args.dur); !reflect.DeepEqual(got, tt.want) {
                t.Errorf("CreateTicker() = %v, want %v", got, tt.want)
            }
        })
    }
}

At the moment when I run the test I get the error message that the objects are not identical.

--- FAIL: TestCreateTicker (0.00s)
    --- FAIL: TestCreateTicker/test. (0.00s)
      CreateTicker() = &{0xc000062360 {824633909248 32883400129906 12000000000 0x471bc0 0xc000062360 0 0 1}}, want &{0xc0000622a0 {824633909248 32871400127913 12 0x471bc0 0xc0000622a0 0 0 1}}
FAIL
...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you really want to test this, you would have to actually measure how long it takes the timer to emit two ticks, and check whether the delta is within an acceptable range. That’s a lot of effort for a test that is not very useful, and your test-to-code ratio is already showing quite a poor return on investment, with 25 lines of test covering a 1 line function.

The better solution is to not test this. It’s a single line that calls out to a standard library function, which you can assume is well tested.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading