Skip to content

Commit

Permalink
Throw exception with meaningful error description in case of missing …
Browse files Browse the repository at this point in the history
…state definition. (#15)

Throwing exception with meaningful error description in case of missing state definition.
  • Loading branch information
Piotr Chmielowski authored and lfernandosp committed May 29, 2019
1 parent 13e6258 commit e45485d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
3 changes: 1 addition & 2 deletions src/main/kotlin/com/tinder/StateMachine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ class StateMachine<STATE : Any, EVENT : Any, SIDE_EFFECT : Any> private construc
private fun STATE.getDefinition() = graph.stateDefinitions
.filter { it.key.matches(this) }
.map { it.value }
.firstOrNull()
.let { checkNotNull(it) }
.firstOrNull() ?: error("Missing definition for state ${this.javaClass.simpleName}!")

private fun STATE.notifyOnEnter(cause: EVENT) {
getDefinition().onEnterListeners.forEach { it(this, cause) }
Expand Down
21 changes: 21 additions & 0 deletions src/test/kotlin/com/tinder/StateMachineTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,27 @@ internal class StateMachineTest {
}
}

class WithMissingStateDefinition {

private val stateMachine = StateMachine.create<String, Int, Nothing> {
initialState(STATE_A)
state(STATE_A) {
on(EVENT_1) {
transitionTo(STATE_B)
}
}
// Missing STATE_B definition.
}

@Test
fun transition_givenMissingDestinationStateDefinition_shouldThrowIllegalStateExceptionWithStateName() {
// Then
assertThatIllegalStateException()
.isThrownBy { stateMachine.transition(EVENT_1) }
.withMessage("Missing definition for state ${STATE_B.javaClass.simpleName}!")
}
}

private companion object {
private const val STATE_A = "a"
private const val STATE_B = "b"
Expand Down

0 comments on commit e45485d

Please sign in to comment.