53. Go - Unit Testing
Unit testing is a way to test "units" of a program code. Units are small sections.
Requires:
- program code
- testing code
Testing Code requirements:
- import "testing"
- Testing function must start with "TestXxx" and arguments must be (t *testing.T)
// t.Log(), logs errors into default output (this is stdout by default, can change)
// t.Fail(), marks the function as failed.
// t.Error("TEST STRING"), is a t.Log() followed by a t.Fail()
// t.Errorf(), format version
Running Tests:
go test
Program Code Example:
package main
import "fmt"
func main() {
    x := "testing string"
    fmt.Println(reverseString(x))
}
func reverseString(x string) string {
    var answer string
    for i := len(x) - 1; i >= 0; i-- {
        answer += string(x[i])
    }
    return answer
}
Testing Code Example:
package main
import "testing"
func TestReverseString(t *testing.T) {
    x := reverseString("testing string")
    if x != "gnirts gnitset" {
        t.Log("ERROR, SHOULD BEEN gnirts gnitset. GOT ", x, "INSTEAD.")
        t.Fail()
    }
}
// Both files are in the same directory/folder and using same package.
Table Tests:
- basically batch testing with structs.
package main
import "testing"
type testStruct struct {
    testString string
    actual     string
}
var testList = []testStruct{
    {"bobb", "bbob"},
    {"abc", "cba"},
    {"123", "321"},
}
func TestReverseString(t *testing.T) {
    for _, e := range testList {
        x := reverseString(e.testString)
        if x != e.actual {
            t.Errorf("ERROR: TEST FAILED. GOT %v instead of %v", x, e.actual)
        }
    }
}
Cover Analysis:
Analysis showing how much of your code are covered by tests. Basically, how many units of your code have been tested to pass.
Commands:
// go test -cover
// this does cover analysis, showing percentage of code covered by tests
// go test -coverprofile FILENAME.out
// exports the analysis to a file.
// go tool cover -html=FILENAME.out
// converts analysis file to html format for visualization
Comments
Post a Comment