I want to write an integration test using Go and MySQL. But I confused how to do this clean. I have 4 functions: create, get, update, and delete. Is it a good practice if I just have one test function to test all my code? For example:
func TestCRUD(t *testing.T){
t.Run("success case", func(t *testing.T){
// call create func
// call update func
// call get func
// call delete func
})
}
If I have code like above, I just have one test function to test all my code. If I want to add a test case, I just add to TestCRUD()
function. Is it a good practice?
Or should I write test function for each CRUD function? So I have 4 test functions and every test function also have many test cases. How can I write my integration test clean?
If you think in maintainability and clean code, IMHO I would recommend you to test each CRUD functions in a different test.
Regarding your question about multiple test cases I would say that a good approach is to use DDT (data-driven-testing or table-driven-testing). Something like:
func Test_create(t *testing.T) {
type args struct {
// Define here your function arguments
arg1 string,
arg2 string,
}
tests := []struct {
name string
args args
want bool // Your possible function output
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := create(tt.args.id); got != tt.want {
t.Errorf("create() = %v, want %v", got, tt.want)
}
})
}
}
Using gotests you can generate clean and nice tests for your functions.