To write unit tests for applications using demoinfocs-golang, you can use the fake package to mock the demoinfocs.Parser interface and other components. This allows you to simulate specific event sequences and parser behaviors (like errors) without needing a real demo file.
Key Mocking Steps:
- Initialize the Mock: Create a new mocked parser using
fake.NewParser(). - Inject Events: Use
parser.MockEvents(...args) to schedule events. The arguments are passed to the mock's internal event map. The index in the slice determines the frame at which the events are emitted (e.g., parser.MockEvents(event1) for frame 0, parser.MockEvents(event2, event3) for frame 1). - Define Method Behavior: Use the
.On("MethodName").Return(value) pattern to define what the mock should return when specific parser methods are called (e.g., ParseToEnd).
import (
"errors"
"testing"
assert "github.com/stretchr/testify/assert"
common "github.com/markus-wa/demoinfocs-golang/v5/pkg/demoinfocs/common"
events "github.com/markus-wa/demoinfocs-golang/v5/pkg/demoinfocs/events"
fake "github.com/markus-wa/demoinfocs-golang/v5/pkg/demoinfocs/fake"
)
func TestCollectKills(t *testing.T) {
parser := fake.NewParser()
kill1 := kill(common.EqAK47)
kill2 := kill(common.EqScout)
kill3 := kill(common.EqAUG)
// Mocking events at specific frames
parser.MockEvents(kill1) // Frame 0
parser.MockEvents(kill2, kill3) // Frame 1
// Mocking method return values
parser.On("ParseToEnd").Return(nil)
actual, err := collectKills(parser)
assert.Nil(t, err)
expected := []events.Kill{kill1, kill2, kill3}
assert.Equal(t, expected, actual)
}
func kill(wep common.EquipmentElement) events.Kill {
eq := common.NewEquipment(wep)
return events.Kill{
Killer: new(common.Player),
Weapon: &eq,
Victim: new(common.Player),
}
}