vitorestevam / FluentRequest

A friendly http wrapper
3 stars 1 forks source link

Simulate operations dinamically in unity tests #5

Open vitorestevam opened 1 year ago

vitorestevam commented 1 year ago

My intent with this is discuss about a way to simulate our Method Chaining dinamically in Tests.

I expect to be able to build a Map with the name of the function and the parameters it uses and using reflection to call this functions over a FluentRequest object. In the following i`ll add an example of how do it works and a PR of this integrated to to project will be linked ASAP.

vitorestevam commented 1 year ago

The objective here is putting into the map the name of the function and its parameter then calling it using reflect.ValueOf(*example{}).MethodByName(method).Call(params)

package main

import (
    "reflect"
    "testing"

    "github.com/stretchr/testify/assert"
)

type example struct {
    content string
    status  int
}

func (e *example) SetContent(value string) *example {
    e.content = value
    return e
}

func (e *example) SetStatus(value int) *example {
    e.status = value

    return e
}

func TestExample(t *testing.T) {
    var tests = []struct {
        options         map[string]interface{}
        expectedContent string
        expectedStatus  int
    }{
        {options: map[string]interface{}{
            "SetContent": "Hello",
            "SetStatus":  1,
        },
            expectedContent: "Hello",
            expectedStatus:  1},
    }

    for _, test := range tests {
        t.Run("", func(t *testing.T) {
            e := &example{}
            for method, parameter := range test.options {
                meth := reflect.ValueOf(e).MethodByName(method)

                params := []reflect.Value{}
                if parameter != nil {
                    params = append(params, reflect.ValueOf(parameter))
                }

                resp := meth.Call(params)

                e = resp[0].Interface().(*example)
            }

            assert.Equal(t, test.expectedContent, e.content)
            assert.Equal(t, test.expectedStatus, e.status)
        })
    }
}
vitorestevam commented 1 year ago

Some problems i`m having with this: