Last active
February 7, 2016 20:16
-
-
Save ppeble/fe86e6559bc0614a0aba to your computer and use it in GitHub Desktop.
Go DI Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Target interface | |
type Repository interface { | |
Add (uuid.UUID) (Account, error) | |
} | |
// This is our test structure. It has an internal function that you can inject. | |
type funcAccountRepo struct { | |
add func(uuid.UUID) (Account, error) | |
} | |
// This is the implementation in our test struct that just calls what we inject. It satisfies the interface but it just calls | |
// whatever we passed in. | |
func (f funcAccountRepo) Add(ssoUuid uuid.UUID) (Account, error) { | |
return f.add(ssoUuid) | |
} | |
// Imagine this is inside your test now. | |
// This is an example of us creating the test struct and injecting a func that returns an empty account when calling | |
// repo.Add() | |
repo := funcAccountRepo{ | |
add: func(uuid.UUID) (Account, error) { return Account{}, nil }, | |
} | |
subject := NewAccountCreate(repo) // Pass the mocked repo in | |
// Now your use case/whatever has a repo as far as it is concerned but it does whatever you specified above in the | |
// function. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment