简体   繁体   中英

golang test spy incorrectly comparing equality

I'm in the process of learning go and am adapting a Java Game of Life example from testdouble . However, the test spy I have written incorrectly compares equality of my World struct - the test passes when it should fail, since output(world) is not being called. What am I doing incorrectly?

Test:

package gameoflife

import (
    "testing"

    "github.com/google/go-cmp/cmp"
)

func TestZeroGenerations(t *testing.T) {
    generatesSeedWorldStub := GeneratesSeedWorldStub{}
    outputsWorldSpy := OutputsWorldSpy{}
    conway := NewSimulatesConway(&generatesSeedWorldStub, &outputsWorldSpy)
    seedWorld := World{}

    conway.simulate()

    correctWorld := outputsWorldSpy.wasOutputCalledWithWorld(seedWorld)
    if !correctWorld {
        t.Errorf("Output called with seed world, expected: %t, got: %t", true, correctWorld)
    }
}

type GeneratesSeedWorldStub struct{}

func (gsw *GeneratesSeedWorldStub) generate() World {
    return World{}
}

type OutputsWorldSpy struct {
    outputCalledWithWorld World
}

func (ow *OutputsWorldSpy) output(world World) {
    ow.outputCalledWithWorld = world
}

func (ow *OutputsWorldSpy) wasOutputCalledWithWorld(world World) bool {
    return cmp.Equal(world, ow.outputCalledWithWorld)
}

Implementation:

package gameoflife

type SimulatesConway struct {
    generatesSeedWorld GeneratesSeedWorld
    outputsWorld       OutputsWorld
}

func NewSimulatesConway(generatesSeedWorld GeneratesSeedWorld, outputsWorld OutputsWorld) SimulatesConway {
    return SimulatesConway{generatesSeedWorld: generatesSeedWorld, outputsWorld: outputsWorld}
}

func (sc *SimulatesConway) simulate() {
    // seedWorld := sc.generatesSeedWorld.generate()
    // sc.outputsWorld.output(seedWorld)
}

type GeneratesSeedWorld interface {
    generate() World
}

type OutputsWorld interface {
    output(world World)
}

type World struct{}

When called outputsWorldSpy := OutputsWorldSpy{} golang assigned default value in outputsWorldSpy.outputCalledWithWorld = World{} and you assigned seedWorld := World{} . So they are same that's why test passed. If you want to handle that case, i suggest to use pointer.

type OutputsWorldSpy struct {
    outputCalledWithWorld *World
}

func (ow *OutputsWorldSpy) output(world World) {
    ow.outputCalledWithWorld = &world
}

func (ow *OutputsWorldSpy) wasOutputCalledWithWorld(world World) bool {
    if ow.outputCalledWithWorld == nil {
        return false
    }
    return cmp.Equal(world, *ow.outputCalledWithWorld)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM