main
 1package mapper
 2
 3import (
 4	"fmt"
 5	"testing"
 6
 7	"github.com/stretchr/testify/assert"
 8	"github.com/stretchr/testify/require"
 9)
10
11type unregisteredType struct{}
12
13type testObject struct {
14	GivenName  string
15	FamilyName string
16}
17
18type testModel struct {
19	Name string
20}
21
22func TestMapper(t *testing.T) {
23	Register[*testObject, *testModel](func(item *testObject) *testModel {
24		return &testModel{
25			Name: fmt.Sprintf("%v %v", item.GivenName, item.FamilyName),
26		}
27	})
28
29	t.Run("MapFrom", func(t *testing.T) {
30		t.Run("when the mapping is registered", func(t *testing.T) {
31			item := &testObject{
32				GivenName:  "Tsuyoshi",
33				FamilyName: "Garret",
34			}
35
36			model := MapFrom[*testObject, *testModel](item)
37
38			require.NotNil(t, model)
39			assert.Equal(t, "Tsuyoshi Garret", model.Name)
40		})
41
42		t.Run("When the mapping is not registered", func(t *testing.T) {
43			item := &unregisteredType{}
44			model := MapFrom[*unregisteredType, *testModel](item)
45
46			assert.Nil(t, model)
47		})
48	})
49
50	t.Run("MapEachFrom", func(t *testing.T) {
51		t.Run("when the mapping is registered", func(t *testing.T) {
52			datum := []*testObject{
53				{GivenName: "Tsuyoshi", FamilyName: "Garret"},
54				{GivenName: "Takashi", FamilyName: "Shirogane"},
55			}
56
57			results := MapEachFrom[*testObject, *testModel](datum)
58
59			require.NotNil(t, results)
60			require.Equal(t, 2, len(results))
61
62			assert.Equal(t, "Tsuyoshi Garret", results[0].Name)
63			assert.Equal(t, "Takashi Shirogane", results[1].Name)
64		})
65
66		t.Run("when the mapping is not registered", func(t *testing.T) {
67			datum := []*unregisteredType{
68				{},
69			}
70
71			results := MapEachFrom[*unregisteredType, *testModel](datum)
72
73			require.NotNil(t, results)
74			assert.Equal(t, 0, len(results))
75		})
76	})
77}