samedi 27 mars 2021

Write test to check for runtimeerrors

I am writing tests for an interpreter that panics for a number of syntactically valid input. This is a minimal example of how I do it:

package minimalexample

import (
    "testing"
)

func access(i int) string {
    return []string{"a", "b"}[i]
}

func TestAccess(t *testing.T) {
    tests := []struct {
        testdatum int
        expected  string
    }{
        {0, "a"},
        {2, ""},
        {1, "c"},
        {4, ""},
    }

    for _, tt := range tests {
        testAccess(tt, t)
    }
}

func testAccess(tt struct {
    testdatum int
    expected  string
}, t *testing.T) {

    defer func() {
        if err := recover(); err != nil {
            t.Errorf("Runtime error for testdatum: %v", tt.testdatum)
        }
    }()
    result := access(tt.testdatum)
    if result != tt.expected {
        t.Errorf("%v evaluates to %q, though it should be %q", tt.testdatum, result, tt.expected)
    }

}

The idea to handle panic is taken from https://golang.org/doc/effective_go#recover, however I do not know whether it is good practice to use it in tests like I do in the above example or there is some reason why it is to be preferred to just let the test fail until the runtime error is fixed.

Aucun commentaire:

Enregistrer un commentaire