From charlesreid1

(Created page with "Testing in Go: Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/ Advanced Go testing tutorial: https://tutorialedge.net/golang/advanced-go-...")
 
No edit summary
Line 1: Line 1:
Testing in Go:
=Basics=
 
==How testing works in Go==
 
For each file <code>X.go</code> a corresponding test named <code>X_test.go</code> should contain unit tests for that code.
 
To run tests, just use the built-in test command in go: <code>go test</code>
 
==Example==
 
Take this simple function as an example:
 
<pre>
package main
 
import (
"fmt"
)
 
// Return the square of a number
func square(x int) (result int) {
return x * x
}
 
func main() {
fmt.Println("Hello World")
}
</pre>
 
We can write a corresponding test:
 
<pre>
package main
 
import (
"testing"
)
 
func test_square(t *testing.T) {
if test_square(2) != 4 {
t.Error("Error testing square(): did not return correct result")
}
}
</pre>
 
=Resources=


Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/
Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/
Line 7: Line 52:




=Flags=


{{GoFlag}}
{{GoFlag}}

Revision as of 03:19, 13 December 2018

Basics

How testing works in Go

For each file X.go a corresponding test named X_test.go should contain unit tests for that code.

To run tests, just use the built-in test command in go: go test

Example

Take this simple function as an example:

package main

import (
	"fmt"
)

// Return the square of a number
func square(x int) (result int) {
	return x * x
}

func main() {
	fmt.Println("Hello World")
}

We can write a corresponding test:

package main

import (
	"testing"
)

func test_square(t *testing.T) {
	if test_square(2) != 4 {
		t.Error("Error testing square(): did not return correct result")
	}
}

Resources

Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/

Advanced Go testing tutorial: https://tutorialedge.net/golang/advanced-go-testing-tutorial/


Flags