Hello,

I am trying out golang and like it's concepts (coming from Python and Java 
mostly, not having Exceptions felt a bit strange at the start, though :-)).

* Now I try to write tests for 
https://github.com/caradojo/trivia/blob/master/go/trivia.go for the fun of 
it. 
* I want to do this without modifying the code (too much).
* I already introduced my own fake[1] random and now need to replace 
os.Stdout with a fake implementation as the results of the game implemented 
here are written with `fmt.Println` resp. `fmt.Printf`.
* My first approach was to use a tempfile[2], this works but I do not like 
to touch the disk during tests.
* In Java `System.out` is just a `PrintStream` which is easily replaced by 
sth. like `System.setOut(new PrintStream(new ByteArrayOutputStream()));`
* Now in golang `os.Stdout` is an `*os.File` which is mostly a wrapper for 
an OS specific file. 

I now tried something like this:
```

type file interface {
 io.Writer
}

type fakeFile struct {
 out *bytes.Buffer
}

func (ff fakeFile) Write(p []byte) (n int, err error) {
 return ff.out.Write(p)
}

func foo()
 realStdout := os.Stdout
defer func() { os.Stdout = realStdout }()
var out []byte
var f file = fakeFile{bytes.NewBuffer(out)}
os.Stdout = &os.File{&f}
)
```

This does not compile but I get "cannot use &f (type *file) as type *os.file in 
field value".

Then I tried a Pythonesque approach, something like this:
```
realStdoutWrite := os.Stdout.Write
defer func() { os.Stdout.Write = realStdoutWrite }()
var outb = bytes.NewBufferString("")
os.Stdout.Write = outb.Write
```
but get "cannot assign to os.Stdout.Write"

In a real world example I would not write to os.Stdout but inject an 
`io.Writer` which would be used, 
so this is more a question whether I miss something or is faking os.Stdout 
really hard?

Any hints appreciated :-)

Regards
Mirko

[1] 
https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs
[2] 
https://github.com/mfriedenhagen/trivia/commit/b8ecec0097bfb4a6e7e2992e1401274cff06c03b#diff-2a08ba5d9ea423f34350a051d2333274R44

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to