lundi 6 juin 2016

Asserting for a specific error using only standard library in golang

Let's suppose I have a function which return base64 encoded string for a file which is located at a specific path.

func getFile(path string) (string, error) {
    imgFile, err := ioutil.ReadFile(path)
    if err != nil {
        return "", fmt.Errorf("Error opening image file: %s", err)
    }

    base64 := base64.StdEncoding.EncodeToString(imgFile)
    return base64, nil
}

Now, I'm writing table driven tests for this function and they right now look like this.

func TestGetFile(t *testing.T) {
    type getFileTest struct {
        Path   string
        Base64 string
        Err    error
    }

    getFileTests := []getFileTest{
        {"", "", nil},
    }
    for _, td := range getFileTests {
        base64, err := getFile(td.Path)
        if err != nil {
            t.Errorf("TestGetFile: Error calling getFile: %s", err)
        }
        if base64 != td.Base64 {
            t.Errorf("TestGetFile: Return values from getFile is not expected: Expected: %s, Returned: %s", td.Base64, base64)
        }
    }

}

Now, current test fails with:-

test.go:18: TestGetFile: Error calling getFile: Error opening image file: open : no such file or directory

How do I assert that I get the right error when I pass empty path to getFile?

Aucun commentaire:

Enregistrer un commentaire