github.com/kaydxh/golang@v0.0.131/tutorial/programming_paradigm/interface.program_test.go (about)

     1  package tutorial
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  )
     7  
     8  //Program to an interface not an implementation
     9  type Country struct {
    10  	Name string
    11  }
    12  
    13  type City struct {
    14  	Name string
    15  }
    16  
    17  type Stringable interface {
    18  	ToString() string
    19  }
    20  
    21  func (c Country) ToString() string {
    22  	return "Country = " + c.Name
    23  }
    24  func (c City) ToString() string {
    25  	return "City = " + c.Name
    26  }
    27  
    28  // Program to an interface not an implementation
    29  func PrintStr(p Stringable) {
    30  	fmt.Println(p.ToString())
    31  }
    32  
    33  func TestPrintStr(t *testing.T) {
    34  	testCases := []struct {
    35  		obj      Stringable
    36  		expected string
    37  	}{
    38  		{
    39  			obj:      Country{"USA"},
    40  			expected: "",
    41  		},
    42  		{
    43  			obj:      City{"Los Angeles"},
    44  			expected: "",
    45  		},
    46  	}
    47  
    48  	for i, testCase := range testCases {
    49  		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
    50  			PrintStr(testCase.obj)
    51  		})
    52  	}
    53  }