Skip to content

Latest commit

 

History

History

example

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

Usecase example

Let's imagine we build a use case for our application:

usecase.go

package example

type UseCase struct {
	Repo UserRepo
}

func (u UseCase) CreateUser(name string) error {
	userId, err := u.Repo.NextId()
	if err != nil {
		return err
	}
	err = u.Repo.Store(userId, name)
	if err != nil {
		return err
	}
	return nil
}

type UserRepo interface {
	NextId() (int, error)
	Store(id int, name string) error
}

Now we have to test CreateUser method. For this, let's generate a table-driven test with the gotests tool:

usecase_test.go

package example

import "testing"

func TestUseCase_CreateUser(t *testing.T) {
	type fields struct {
		Repo UserRepo
	}
	type args struct {
		name string
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		wantErr bool
	}{
		// TODO: Add test cases.
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			u := UseCase{
				Repo: tt.fields.Repo,
			}
			if err := u.CreateUser(tt.args.name); (err != nil) != tt.wantErr {
				t.Errorf("CreateUser() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

Now the placeholder // TODO: Add test cases. needs to be filled. For this, call the stubgen command:

stubgen --inp-file ./example/usecase.go --out-file ./example/usecase_stub.go

usecase_stub.go

// Code generated by stubgen; DO NOT EDIT.

package example

type StubUserRepo struct {
	NextIdRes0 int
	NextIdRes1 error
	StoreRes0  error
}

func (s StubUserRepo) NextId() (int, error) {
	return s.NextIdRes0, s.NextIdRes1
}

func (s StubUserRepo) Store(id int, name string) error {
	return s.StoreRes0
}

Now we can fill in the placeholder in the test table:

usecase_test.go

package example

import "testing"

func TestUseCase_CreateUser(t *testing.T) {
	type fields struct {
		Repo UserRepo
	}
	type args struct {
		name string
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		wantErr bool
	}{
		{
			name: "happy path",
			fields: fields{
				Repo: StubUserRepo{
					NextIdRes0: 1,
					NextIdRes1: nil,
					StoreRes0:  nil,
				},
			},
			args: args{
				name: "user",
			},
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			u := UseCase{
				Repo: tt.fields.Repo,
			}
			if err := u.CreateUser(tt.args.name); (err != nil) != tt.wantErr {
				t.Errorf("CreateUser() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}