Another linguistics at Golang (11) - the use of package and test

Go born to support good project management experience and design.

package

In the practice of software engineering, we will encounter many functions duplicate code, such as removing the string end to end spaces. Features high-quality software products is part of its code can be reused, such as every time you do not have to write a function to remove the string end to end spaces.

We have said above variables, structures, interfaces, functions, etc., in fact a so-called bag, is to use some of these many variables, structures, interfaces, and functions placed in a unified logical block. And give them a name, this name is called the package name.

For example, most of us use fmt package above, this package offers a lot of functions to format the output, you can refer to this package in your own code, do formatted output, without having to go every time you write a function. A mature language will provide the basis for a fully functional package for people to call.

There are three benefits of using the package

  1. Repeating function name can be reduced, because of the different functions with the same name in the package may be present. Otherwise too, you have to give these functions with the prefix or suffix to show the difference.
  2. Packages and other organizations to function together, allowing you to find and reuse. For example, you want to use Println () function outputs a string line, you can easily know it fmt package, come with a direct reference to it.
  3. Use the package can be accelerated program to compile. Because the package is precompiled, you have to change the code yourself time, do not have to pack every time I go to compile it.

Creating a Package

We now give an example that demonstrates the Go project management.

First, we in the directory /Users/jemy/JemyGraw/GoLangto create a folder below pkg_demo. Then pkg_democreated inside srcthe folder
. Then in maincreate a folder inside main.gothe file. In addition to the presentation of the package is created, we have srcthe following directory create the folder net.duokr, and then in net.duokrto create a folder inside the mathfolder, the folder name is the name of this folder package go file below. Then we create a math_pkg.gofile, the reason for that name rather than math.gojust do not need to explain this consistent file name and the package name. Then we created a math_pkg_test.gofile as a test case package file. Overall structure is as follows:

.
└── src
    ├── main
    │   ├── build.sh
    │   └── main.go
    └── net.duokr
        └── math
            ├── math_pkg.go
            └── math_pkg_test.go

Build.sh is where we have to compile the project and wrote the script, because the compiler project needs a few commands, write it in the script file easy to use. In addition, to enable build.sh able to perform, using the chmod +x build.shgiven executable permissions for it. The following is build.bat Windows build scripts.
Let's look at math_pkg.gothe definition:

package math
func Add(a, b int) int {
    return a + b
}
func Subtract(a, b int) int {
    return a - b
}
func Multiply(a, b int) int {
    return a * b
}
func Divide(a, b int) int {
    if b == 0 {
        panic("Can not divided by zero")
    }
    return a / b
}

The first is the package name, followed by several function definitions, here we will find them 函数定义首字母都是大写, Go规定了只有首字母大写的函数才能从包导出使用,即其他调用这个包中函数的代码只能调用那些导出的函数.

Let's look at main.gothe definition:

package main
import (
    "fmt"
    math "net.duokr/math"
)
func main() {
    var a = 100
    var b = 200
    fmt.Println("Add demo:", math.Add(a, b))
    fmt.Println("Substract demo:", math.Subtract(a, b))
    fmt.Println("Multiply demo:", math.Multiply(a, b))
    fmt.Println("Divide demo:", math.Divide(a, b))
}

In main.go inside, we use the import keyword refers to our custom packages math, quote method is to start from the main pack parallel file folder net.duokr, back to keep the package name math. That which we give this long package name from an alias called math. Then the function math package inside each call.

Finally, we look at our build script:

export GOPATH=$GOPATH:/Users/jemy/JemyGraw/GoLang/pkg_demo
export GOBIN=/Users/jemy/JemyGraw/GoLang/pkg_demo/bin
go build net.duokr/math
go build main.go
go install main

The first line, we will join the project path GOPATH, so a little later compiled main.go time to find our custom packages;

The second line, we set the installation directory of the project, the fifth line of command the compiled files into this directory;

The third line, we compile our custom packages;

The fourth line, we compile our main.go file;

Fifth row, will install the compiled file to the specified directory.

There is also a Windows compiled the following script build.bat:

@echo off
set GOPATH=GOPATH;C:\JemyGraw\GoLang\pkg_demo
set GOBIN=C:\JemyGraw\GoLang\pkg_demo\bin
go build net.duokr\math
go build main.go
go install main

This time the folder structure:

.
├── bin
│   └── main
├── pkg
│   └── darwin_386
│       └── net.duokr
│           └── math.a
└── src
    ├── main
    │   ├── build.bat
    │   ├── build.sh
    │   ├── main
    │   └── main.go
    └── net.duokr
        └── math
            ├── math_pkg.go
            └── math_pkg_test.go

Run it, output is:

Add demo: 300
Substract demo: -100
Multiply demo: 20000
Divide demo: 0

Well, using the package introductions, we'll look at how to write test cases.

 

test

In the above example, we found that our custom packages defined below math_pkg_test.go there is a file that contains a number of test cases in this package. Go and put to _test.gothe end of the file as a test file.

Test how to write, of course, is to determine whether to run assert result of the program and expected the same.

Let's look at the math test case package.

package math
import (
    "testing"
)
func TestAdd(t *testing.T) {
    var a = 100
    var b = 200
    var val = Add(a, b)
    if val != a+b {
        t.Error("Test Case [", "TestAdd", "] Failed!")
    }
}
func TestSubtract(t *testing.T) {
    var a = 100
    var b = 200
    var val = Subtract(a, b)
    if val != a-b {
        t.Error("Test Case [", "TestSubtract", "] Failed!")
    }
}
func TestMultiply(t *testing.T) {
    var a = 100
    var b = 200
    var val = Multiply(a, b)
if val != a*b { t.Error("Test Case [", "TestMultiply", "] Failed!") } } func TestDivideNormal(t *testing.T) { var a = 100 var b = 200 var val = Divide(a, b) if val != a/b { t.Error("Test Case [", "TestDivideNormal", "] Failed!") } }

The path to switch to the directory where the test file, run the go testcommand, go automatically test all test cases.

In the example above, the test is based on the characteristics of the function name to Teststart, but also the only parameter t *testing.T. summary

Pack and Go test use cases provide a basis to build great software products, as long as we continue to learn, hard to do, you can do well.

 
 
 

 

Guess you like

Origin www.cnblogs.com/tianyamoon/p/11097374.html