Imagine your project currently have 0% unit test code coverage.
And your boss keep pushing it to 80% or even 90%?
What do you do?
Give up?
What if I tell you there is a way?
Not entirely cheating but ... you know, there is always trade off.
If your purpose is to test carefully all path, check if all return is correctly.
Sadly this post is not for you, I guess.
If you only want good number on test coverage, with minimum effort as possible, I hope this will show you some idea you can use :)
In my opinion, unit test is not that important (like must must have).
It's just make sure your code is running excatly as you intent it to be.
If you don't think about edge case before, unit test won't help you.
## First, rewrite the impossible (to test) out
When I learn to programming, I encounter very interesting idea, which become mainly my mindset when I dev later.
I don't recall it clearly, kinda like: "Don't just fix bugs, rewrite so that kind of bugs will not appear later".
So in our context, there is some thing we hardly or can not write test in Go.
My solution is don't use that thing.
In my experience, I can list a few things here:
- Read config each time call func (`viper.Get...`). You can and you should init all config when project starts.
- Not use Dependency Injection (DI). There are too many posts in Internet tell you how to do DI properly.
- Use global var (Except global var `Err...`). You should move all global var inside your struct.
## Let the fun (writing test) begin
If you code Go long enough, you know table driven tests and how is that so useful.
You set up test data, then you test.
Somewhere in the future, you change the func, then you need to update test data, then you good!
In simple case, your func only have 2 or 3 inputs table drive tests still looking good.
But real world is ugly (maybe not, idk I'm just too young in this industry :). Your func can have 5 or 10 inputs, also your func call many third party services.
Imagine having below func to upload image:
```go
type service struct {
db DB
redis Redis
minio MinIO
logService LogService
verifyService VerifyService
}
func (s *service) Upload(ctx context.Context, req Request) error {
// I simplify by omit the response, only care error fow now
if err := s.verifyService.Verify(req); err != nil {
return err
}
if err := s.minio.Put(req); err != nil {
return err
}
if err := s.redis.Set(req); err != nil {
return err
}
if err := s.db.Save(req); err != nil {
return err
}
if err := s.logService.Save(req); err != nil {
return err
}
return nil
}
```
With table driven test and thanks to [stretchr/testify](https://github.com/stretchr/testify), I usually write like this:
Same idea but still with table, you can find here [Functional table-driven tests in Go - Fatih Arslan](https://arslan.io/2022/12/04/functional-table-driven-tests-in-go/).