Skip to content

Instantly share code, notes, and snippets.

@evalphobia
Last active January 18, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evalphobia/3af985a23cfe35966ed7 to your computer and use it in GitHub Desktop.
Save evalphobia/3af985a23cfe35966ed7 to your computer and use it in GitHub Desktop.
テストコード02
package main
import (
"bytes"
"io"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMain(t *testing.T) {
assert := assert.New(t)
m := &StdoutMock{}
m.Set()
main()
output := m.Get()
assert.Equal("2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97", output)
}
type StdoutMock struct {
stdout *os.File
stderr *os.File
writer *os.File
output chan string
}
func (m *StdoutMock) Set() {
backupOut := os.Stdout
backupErr := os.Stderr
r, w, _ := os.Pipe()
os.Stdout = w
os.Stderr = w
opChan := make(chan string)
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
opChan <- buf.String()
}()
m.stdout = backupOut
m.stderr = backupErr
m.writer = w
m.output = opChan
}
func (m *StdoutMock) Get() string {
m.writer.Close()
os.Stdout = m.stdout
os.Stderr = m.stderr
return <-m.output
}
@evalphobia
Copy link
Author

問題 2 のテストコード
https://gist.github.com/bsoo/bd361a7fe01fc6bff068

以下で実行できます。
(解答の関数は main で作って下さい)

# テストライブラリのインストール
$ go get github.com/stretchr/testify/assert

$ ls -l
main.go    # <- 解答のコード
main_test.go # <- ↑に書いてあるテストコード

# テスト実行
$ go test .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment