Golang单元测试用户输入

huangapple go评论89阅读模式
英文:

Golang unit testing user input

问题

我正在尝试以测试驱动开发(TDD)的思维方式学习Go语言。我在理解测试方面遇到了困难。

在下面的示例中,我提示用户输入,进行一些验证并打印结果。我为此编写了一个测试(测试通过),但我觉得它没有触发验证部分,所以我做错了什么。希望能得到一些建议。

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
)

func main() {
	response := askQuestion("What is your name?")
	fmt.Printf("Hello %s\n", response)
}

func askQuestion(question string) string {
	reader := bufio.NewReader(os.Stdin)
	answer := ""

	for {
		fmt.Printf("%s\n", question)
		input, err := reader.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				panic(err)
			}
			break
		}

		if regexp.MustCompile(`[A-Z]{5}`).MatchString(strings.TrimSpace(input)) == true {
			answer = strings.TrimSpace(input)
			fmt.Printf("You entered %s\n", answer)
			break
		} else {
			fmt.Printf("3[31mYou must enter only 5 upper case letters.\n3[0m")
			continue
		}
	}

	return answer
}
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"reflect"
	"strings"
	"testing"
)

func TestAskQuestion(t *testing.T) {
	expected := "foo"
	entered := "foo"

	askQuestion("What is your last name?")

	oldStdout := os.Stdout
	r, w, _ := os.Pipe()

	os.Stdout = w
	fmt.Println(entered)

	outC := make(chan string)
	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()

	}()

	w.Close()
	os.Stdout = oldStdout
	out := strings.TrimSpace(<-outC)

	b, _ := ioutil.ReadAll(os.Stdin)
	t.Log(string(b))

	if !reflect.DeepEqual(expected, out) {
		t.Fatalf("Test Status Failure Issue. Got: '%v' expected %s", out, expected)
	}
}

以上是你提供的代码。

英文:

I am trying to learn go with a TDD mindset. I am stuck getting my head wrapped around testing.

In the example below, I am prompting a user for input, doing a little validation and printing the results. I wrote a test for it (which is passing) however I don't feel like it is hitting the validation portion, so I am doing something wrong. Any advice would be appreciated.

https://play.golang.org/p/FDpbof9Y20

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;io&quot;
	&quot;os&quot;
	&quot;regexp&quot;
	&quot;strings&quot;
)

func main() {
	response := askQuestion(&quot;What is your name?&quot;)
	fmt.Printf(&quot;Hello %s\n&quot;,response)
}

func askQuestion(question string) string {
	reader := bufio.NewReader(os.Stdin)
	answer := &quot;&quot;

	for {
		fmt.Printf(&quot;%s\n&quot;, question)
		input, err := reader.ReadString(&#39;\n&#39;)
		if err != nil {
			if err != io.EOF {
				panic(err)
			}
			break
		}

		if regexp.MustCompile(`[A-Z]{5}`).MatchString(strings.TrimSpace(input)) == true {
			answer = strings.TrimSpace(input)
			fmt.Printf(&quot;You entered %s\n&quot;, answer)
			break
		} else {
			fmt.Printf(&quot;3[31mYou must enter only 5 upper case letters.\n3[0m&quot;)
			continue
		}
	}

	return answer
}

https://play.golang.org/p/WcI4CRfle5

package main

import (
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;io&quot;
	&quot;io/ioutil&quot;
	&quot;os&quot;
	&quot;reflect&quot;
	&quot;strings&quot;
	&quot;testing&quot;
)

func TestAskQuestion(t *testing.T) {
	expected := &quot;foo&quot;
	entered := &quot;foo&quot;

	askQuestion(&quot;What is your last name?&quot;)

	oldStdout := os.Stdout
	r, w, _ := os.Pipe()

	os.Stdout = w
	fmt.Println(entered)

	outC := make(chan string)
	go func() {
		var buf bytes.Buffer
		io.Copy(&amp;buf, r)
		outC &lt;- buf.String()

	}()

	w.Close()
	os.Stdout = oldStdout
	out := strings.TrimSpace(&lt;-outC)

	b, _ := ioutil.ReadAll(os.Stdin)
	t.Log(string(b))

	if !reflect.DeepEqual(expected, out) {
		t.Fatalf(&quot;Test Status Failure Issue. Got: &#39;%v&#39; expected %s&quot;, out, expected)
	}
}

答案1

得分: 2

Go的测试需要放在以xyz_test.go命名的文件中,所以Playground不是熟悉单元测试功能的正确地方。

如果你在本地安装了Go,请运行命令go help test,以获得一个非常简要的介绍。

英文:

Go's tests need to live in files which are named xyz_test.go, so the playground is not the right place to familiarize yourself with the unit testing feature.

If you have go installed locally, run the command go help test, to get a very brief introduction.

huangapple
  • 本文由 发表于 2015年12月18日 08:00:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/34346496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定