mardi 8 octobre 2019

Testing Go Loops

I'm learning about unit testing in Go, and am new to unit testing in general. I've written some unit tests on functions who's purpose is to do calculations and return the results, but am now stuck trying to test a function that loops over values.

func main() {
    tryRounding()
}

func tryRounding() {
    var i []int

    k := []int{12, 13, 131, 259}
    for n := 0; n < len(k); n++ {
        i = append(i, n)
        i[n] = roundToInt(k[n], 5)
        fmt.Println(giveAnswer(k[n], i[n]))
    }
}

func giveAnswer(num int, res int) string {
    return fmt.Sprintf("For input %d, rounding to nearest 5, we get %d\n", num, res)
}

For the giveAnswer function, the test is simple.

func TestGiveAnswer(t *testing.T) {
    result := giveAnswer(12, 10)
    if result != "For input 12, rounding to nearest 5, we get 10\n" {
       t.Errorf("Printed Incorrectly.")
    }
}

I dont understand how to approach testing something that doesn't have an obvious "I give you this, you do that, I want this that way" approach. Is there a way to write tests for code like in tryRounding? Also, is there a way to cover the main function's call to tryRounding?

Aucun commentaire:

Enregistrer un commentaire