Creating a test

Report a typo

A colleague gave you her function to test. Write a test that checks that the function works correctly. Sum(a, b) should return a + b.

Use t.Errorf(...) to display the message that the test has failed (if the expected result is not equal to the real one). If your test is correct, the system will display OK.

Sample Input 1:

Sample Output 1:

OK
Write a program in Go
package main

import (
"fmt"
"reflect"
"testing"
)

var Sum func(a, b int) int // nolint: gochecknoglobals // DO NOT delete this comment!

func TestSum(t *testing.T) {
// write a test that checks Sum implementation
}

// DO NOT MODIFY
func main() {
var t testing.T

Sum = func(a, b int) int { return a + b }

TestSum(&t)
if reflect.ValueOf(&t).Elem().FieldByName("common").FieldByName("failed").Bool() {
fmt.Println("The test is incorrect!")
return
}

Sum = func(a, b int) int { return a + b * 2}

TestSum(&t)
if !reflect.ValueOf(&t).Elem().FieldByName("common").FieldByName("failed").Bool() {
fmt.Println("The test is incorrect!")
return
}

fmt.Println("OK")
}
___

Create a free account to access the full topic