github.com/d0ngw/go@v1.1.40/inject/inject_helper_test.go (about)

     1  package inject
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  type config struct {
    12  	Name string `yaml:"name"`
    13  
    14  	needModule bool
    15  }
    16  
    17  func (p *config) Parse() error {
    18  	return nil
    19  }
    20  
    21  func (p *config) ConfModule() (module *Module, err error) {
    22  	if !p.needModule {
    23  		return
    24  	}
    25  	module = NewModule()
    26  	module.BindWithName("hello", 2021)
    27  	return
    28  }
    29  
    30  type userService struct {
    31  	Injector *Injector `inject:"_"`
    32  	Hello    int       `inject:"hello,optional"`
    33  }
    34  
    35  func (p *userService) Init() error {
    36  	if p.Injector == nil {
    37  		return errors.New("invalid Injector")
    38  	}
    39  	return nil
    40  }
    41  
    42  func TestSetupInjector(t *testing.T) {
    43  	conf := &config{}
    44  	module := NewModule()
    45  	svc := &userService{}
    46  	module.Bind(svc)
    47  
    48  	err := os.Chdir("testdata")
    49  	injector, err := SetupInjector(conf, "", "dev", module)
    50  	assert.NoError(t, err)
    51  	assert.NotNil(t, injector)
    52  	assert.NotNil(t, svc.Injector)
    53  	assert.EqualValues(t, 0, svc.Hello)
    54  
    55  	conf.needModule = true
    56  	svc = &userService{}
    57  	module = NewModule()
    58  	module.Bind(svc)
    59  	injector, err = SetupInjector(conf, "", "dev", module)
    60  	assert.NoError(t, err)
    61  	assert.NotNil(t, injector)
    62  	assert.NotNil(t, svc.Injector)
    63  	assert.EqualValues(t, 2021, svc.Hello)
    64  }