Skip to content
Joshua Smith edited this page Aug 22, 2024 · 5 revisions

Trial Guide

Trial Template

type input struct {}
fn := func(in input) (any, error) {
    // TODO: setup test case, call routine and return result
    return nil, nil
}
cases := trail.Cases[input,any]{
    "default": {
        Input:    input{},
        Expected: 1,
    },
}
trial.New(fn,cases).Test(t)

Examples

Test an addition function

func Add(i1, i2 int) int {
	return i1 + i2
}

func TestAdd(t *testing.T) {
	testFn := func(in trial.Input) (int, error) {
		return Add(in.Slice(0).Int(), in.Slice(1).Int()), nil
	}
	cases := trial.Cases[trial.Input, int]{
		"Add two numbers": {
			Input:    trial.Args(1, 2),
			Expected: 3,
		},
	}
	trial.New(testFn, cases).Test(t)
}
  // Output: PASS: "Add two numbers"

Test string to int conversion

func TestStrconv_Itoa(t *testing.T) {
	cases := trial.Cases[string, int]{
		"valid int": {
			Input:    "12",
			Expected: 12,
		},
		"invalid int": {
			Input:     "1abe",
			ShouldErr: true,
		},
	}
	trial.New(strconv.Atoi, cases).Test(t)
}


// Output: PASS: "valid int"
// PASS: "invalid int"

Test divide method

func TestDivide(t *testing.T) {
	fn := func(in []int) (int, error) {
		return Divide(in[0], in[1]), nil
	}
	cases := trial.Cases[[]int, int]{
		"1/1": {
			Input:    []int{1, 1},
			Expected: 1,
		},
		"6/2": {
			Input:    []int{6, 2},
			Expected: 1,
		},
		"divide by zero": {
			Input:       []int{1, 0},
			ShouldPanic: true,
		},
	}
	trial.New(fn, cases).Test(t)
}

// Output: PASS: "1/1"
// FAIL: "6/2"
// PASS: "divide by zero"

test json.Unmarshal

func TestMarshal(t *testing.T) {
	type output struct {
		Name  string
		Count int
		Value float64
	}
	fn := func(s string) (output, error) {
		v := output{}
		err := json.Unmarshal([]byte(s), &v)
		return v, err
	}
	cases := trial.Cases[string, output]{
		"valid": {
			Input:    `{"Name":"abc", "Count":10, "Value": 12.34}`,
			Expected: output{Name: "abc", Count: 10, Value: 12.34},
		},
		"invalid type": {
			Input:       `{"Value", "abc"}`,
			ExpectedErr: errors.New("invalid character"),
		},
		"invalid json": {
			Input:     `{`,
			ShouldErr: true,
		},
	}
	trial.New(fn, cases).SubTest(t)
}

/*
Output
 PASS: TestMarshal (0.00s)
    --- PASS: TestMarshal/valid (0.00s)
    --- PASS: TestMarshal/invalid_json (0.00s)
    --- PASS: TestMarshal/invalid_type (0.00s)
*/ 
Clone this wiki locally