# How to test an event-sourced command?
Open the respective command test suite, ex: CreateCommandTestSuite.scala
Grab the CommandFixture, provide
- provide
giveni.e. given these events (zero or more) have occured. - provide
wheni.e. given this command input - verify the events raised i.e.
expectEventRaised
For example:
When a valid input is provided to the command, event
LotteryCreatedmust be raised:test("create first lottery", Tag("create"), ptest) { grab[CreateCommandFixture] .given() .when(Input("TestLottery", 200)) .expectEventRaised(EventRaised(LotteryCreated("TestLottery", 200))) }Given a lottery has already been created & ran, when you try to create another lottery - the event should be raised successfully.
test("create another lottery", Tag("create"), ptest) { grab[CreateCommandFixture] .given(LotteryCreated(lotteryName = "FirstLottery", amount = 1000), ParticipantAdded(lotteryName = "FirstLottery", participantName = "Alok", email = "alok@gmail.com"), ParticipantAdded(lotteryName = "FirstLottery", participantName = "Banu", email = "banu@gmail.com"), LotteryRan(lotteryName = "FirstLottery", winner = "Alok")) .when(Input("TestLottery", 200)) .expectEventRaised(EventRaised(LotteryCreated("TestLottery", 200))) }To verify the event data use
expectEventRaisedMatchtest("lottery data match", Tag("create"), ptest) { grab[CreateCommandFixture] .given() .when(Input("TestLottery", 200)) .expectEventRaisedMatch("Lottery name must be TestLottery")(e => e.created.lotteryName == "TestLottery") .expectEventRaisedMatch("Lottery amount must be 200")(e => e.created.amount == 200) }To print the events raised use
printEventRaisedtest("lottery data match", Tag("create"), ptest) { grab[CreateCommandFixture] .given() .when(Input("TestLottery", 200)) .printEventRaised .expectEventRaisedMatch("Lottery amount must be 200")(e => e.created.amount == 200) }To run the event handlers in order to assert the state in writeDb use
runEventHandlers()test("lottery data match", Tag("create"), ptest) { grab[CreateCommandFixture] .given() .when(Input("TestLottery", 200)) .expectEventRaisedMatch("Lottery amount must be 200")(e => e.created.amount == 200) .runEventHandlers() val lotteryExists = LotteryQuery().lotteryName.is("TestLottery").exists assert(lotteryExists, "Lottery has not been created") }
- provide
Run the testcase:
[LotteryDomain] testOnly *CreateCommandTestSuite -- -n create
Note:
- Best practice is to separate the write database for test-cases using env specific configuration