#golang

go test code 작성하기

이번 포스트에서는 go 언어로 test code를 작성하는 법을 알아보도록 한다.

먼저, go 에서 test code를 작성하기 위해서는 다음과 같은 규약을 따라야 한다.

  • 테스트 함수의 이름은 Test... 가 되어야 한다.
  • 테스트 함수는 t *testing.T 만을 입력값으로 받는다.
  • test code가 작성된 파일의 이름은 뒤가 _test.go 가 되어야 한다.

유용한 testing 함수와 활용방안

t.Error & t.Errorf

t.Error 함수는 문제가 일어나는 지점에서 에러를 발생시키며 좀 더 자세한 오류의 내용을 명시하고 싶은 경우 t.Errorf 를 사용한다.

example

1
2
3
4
5
6
func TestSum(t *testing.T) {
total := Sum(5, 5)
if total != 10 {
t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
}
}

t.Log

t.Log는 테스트 진행 중 콘솔창에 나타내고 싶은 말들을 명시한다.
어떤 입력값이 입력되는 지를 나타내거나 혹은 절차에 관한 간략한 설명을 곁들이는 것이 좋다.

example

1
2
3
4
5
6
7
func TestSum(t *testing.T) {
total := Sum(5, 5)
t.Log("testing sum function... input data: %d, %d", 5, 5)
if total != 10 {
t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
}
}

Test Table

테스트 하고자 하는 입출력 값을 table에 담아 보다 보기 좋게 명시할 수 있으며 다음과 같이 사용될 수 있다.

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main_test

import "testing"
func Sum(a int, b int) int{

return a+b
}
func TestSum(t *testing.T) {
tests := map[string]struct{
input struct{
testData1 string
testData2 string
}
output struct{
testOutput1 string
testOutput2 string
}
err error
}{
input: struct{
testData1: "test data 1",
testData2: "test data 2",
},
output: struct{
testOutput1: "test output 1",
testOutput2: "test output 2",
}
}

for testName, test := range tests{
Sum(test)
}
}

mock 객체를 활용한 test 시의 dependency 처리

go 함수 내에 dependency injection이 있는 경우 일일히 모든 dependency들을 세팅해 주는 것은 테스트의 코스트가 너무 커진다.
때문에 테스트를 위한 fake interface를 구현하여 inject 해 줌으로써 해결한다.


Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×