Created
June 3, 2019 13:08
-
-
Save nvtuan305/36f5f233610960de1033c2a16fbb29cf to your computer and use it in GitHub Desktop.
test_example
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"errors" | |
"testing" | |
"github.com/stretchr/testify/assert" | |
) | |
type User struct { | |
Id int64 | |
Email string | |
Role string | |
} | |
type UserServiceInter interface { | |
GetUserInfoById(userId int64) (User, error) | |
} | |
type UserServiceImpl struct {} | |
func (us *UserServiceImpl) GetUserInfoById(userId int64) (User, error) { | |
var user User | |
// Get user from db or other services... | |
// Get user from db or other services... | |
return user, nil // user or error | |
} | |
type UserServiceMock struct {} | |
func (us *UserServiceMock) GetUserInfoById(userId int64) (User, error) { | |
if userId <= 0 { | |
return nil, errors.New("invalid user id") | |
} | |
if userId == 1 { | |
return User{ | |
Id: userId, | |
Email: "[email protected]", | |
Role: "guest", | |
}, nil | |
} | |
return User{ | |
Id: userId, | |
Email: "[email protected]", | |
Role: "admin", | |
}, nil | |
} | |
func isAdminUser(userService UserServiceInter, userId int64) bool { | |
user, err := userService.GetUserInfoById(userId) | |
if err != nil { | |
return false | |
} | |
return user.Role == 'admin' | |
} | |
// TEST | |
func isAdminUser_Test(t *testing.T) { | |
var userServiceMock = UserServiceMock{} | |
var userId | |
var isAdmin | |
// Test case 1 | |
userId = -1 | |
isAdmin = isAdminUser(userServiceMock, userId) | |
assert.Equal(t, false, isAdmin, "Failed") | |
// Test case 1 | |
userId = 0 | |
isAdmin = isAdminUser(userServiceMock, userId) | |
assert.Equal(t, false, isAdmin, "Failed") | |
// Test case 1 | |
userId = 1 | |
isAdmin = isAdminUser(userServiceMock, 1) | |
assert.Equal(t, false, isAdmin, "Failed") | |
// Test case 1 | |
userId = 3 | |
isAdmin = isAdminUser(userServiceMock, userId) | |
assert.Equal(t, true, isAdmin, "Failed") | |
} | |
// Main function | |
func main() { | |
// Do something... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment