Home > OS >  Return map of structs with testing expectations Go
Return map of structs with testing expectations Go

Time:10-13

How do you declare a map of structs? The following firstFactorial_tests.go file:

package firstFactorial

import (
    "testing"

    "github.com/google/go-cmp/cmp"
)

func useCases() map[string]struct {
    tests := map[string]struct {
        input int
        want int
    }{
        "regular_number": {input: 3, want: 6},
        "high_number": {input: 18, want: 6.402373705728e 15},
        "zero": {input: 0, want: 1},
        "one": {input: 1, want: 1},
    }

    return tests
}

func TestRegular(t *testing.T) {
    for name, tc := range useCases() {
        t.Run(name, func(t *testing.T) {
            got := firstFactorial(tc.input)
            if diff := cmp.Diff(tc.want, got); diff != "" {
                t.Fatalf("%s: expected: %v, got %v", name, tc.want, got)
            }
        })
    }
}

func TestRecursive(t *testing.T) {
    for name, tc := range useCases() {
        t.Run(name, func(t *testing.T) {
            got := firstFactorialRecursive(tc.input, 1)
            if diff := cmp.Diff(tc.want, got); diff != "" {
                t.Fatalf("%s: expected: %v, got %v", name, tc.want, got)
            }
        })
    }
}

Returns the following:

$ go test
# github.com/PZ01/coding-problems-go/firstFactorial
firstFactorial_test.go:10:11: expected type, found ':='
FAIL    github.com/PZ01/coding-problems-go/firstFactorial [setup failed]

Source file:

package firstFactorial

func firstFactorial(num int) int {
    factorial := 1

    for num > 0 {
        factorial *= num
        num--
    }

    return factorial
}

func firstFactorialRecursive(num int, factorial int) int {
    if num <= 0 {
        return factorial
    }

    factorial *= num
    num--

    return firstFactorialRecursive(num, factorial);
}

Also, any suggestion on making this more compact is appreciated.


Golang 1.7

CodePudding user response:

Use a anonymous structs as map value definition.

func useCases() map[string]struct{ input, want int } {
    return map[string]struct{ input, want int }{
        "regular_number": {input: 3, want: 6},
        "high_number":    {input: 18, want: 6.402373705728e 15},
        "zero":           {input: 0, want: 1},
        "one":            {input: 1, want: 1},
    }
}

PLAYGROUND

  •  Tags:  
  • go
  • Related