I saw many blogs where they write how to do unit testing but I will understand theory portion and not understand how to implement the test case can anyone will tell me that how will I implement the first test case for more understanding with the unit testing. Here I'm implementing the small program for average:-
Folder structure is:-
main.go
average(Folder)----> math_test.go
code in the both file is:-
main.go
package main
import "fmt"
import "testcases/average"
func main() {
xs := []float64{1,2,3,4}
avg := m.Average(xs)
fmt.Println(avg)
}
math_test.go
package math
import "testing"
func TestAverage(t *testing.T) {
var v float64
v = Average([]float64{1,2})
if v != 1.5 {
t.Error("Expected 1.5, got ", v)
}
}
ERROR:- go build testcases/average: no non-test Go files in /home/iron/go/src/testcases/average
Helping me I'm very thankful to you.
You have to change the package name with the main
or math
as @mkopriva and @whitespace said and place them into the same folder see in example
main.go
package main
func Sum(x int, y int) int {
return x + y
}
func main() {
Sum(5, 5)
}
math_test.go
package main
import "testing"
func TestSum(t *testing.T) {
total := Sum(5, 5)
if total != 10 {
t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
}
}
Output:-
PASS ok testcases 0.001s
And also a basic example of the testing.
this is because your test file is in package main
. You can either change your main.go to have package math
, or change your math_test.go
to package main
. Check my git repo, here I have not written any main function. Yet functions are written, and their output is checked with testing
package.