54. Go - Example Testing

Example testing is like Unit Testing but for example codes in documentations.

Requires:
- main/source code
- testing code that tests a function from source code.

Run example test:
go test

Main Code Example:
package main

func combineString(a, b string) string {
    x := a + b
    return x
}


Test Code Example:
// correct output of function = "applebox"
package main

import "fmt"

func ExampleCombineString() {
    fmt.Println(combineString("apple", "box"))
    // Output: applebox
}


// the output comment block is a valid syntax for testing the example function.
// Must have "Output:"
// Anything to the right or below the output comment will be checked for validity (if test fails, it is because output of function does not match the one in the comment block.

Test Code Example: 
// correct output of function = "applebox"
// output comment wants "apple box"
package main

import "fmt"

func ExampleCombineString() {
    fmt.Println(combineString("apple", "box"))
    // Output: apple box
}


// an error and statement showing the test has failed.

--- FAIL: ExampleCombineString (0.00s)
got:
applebox
want:
apple box
FAIL
exit status 1

Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort