Skip to content

Commit e45485d

Browse files
Piotr Chmielowskilfernandosp
authored andcommitted
Throw exception with meaningful error description in case of missing state definition. (#15)
Throwing exception with meaningful error description in case of missing state definition.
1 parent 13e6258 commit e45485d

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/main/kotlin/com/tinder/StateMachine.kt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ class StateMachine<STATE : Any, EVENT : Any, SIDE_EFFECT : Any> private construc
5151
private fun STATE.getDefinition() = graph.stateDefinitions
5252
.filter { it.key.matches(this) }
5353
.map { it.value }
54-
.firstOrNull()
55-
.let { checkNotNull(it) }
54+
.firstOrNull() ?: error("Missing definition for state ${this.javaClass.simpleName}!")
5655

5756
private fun STATE.notifyOnEnter(cause: EVENT) {
5857
getDefinition().onEnterListeners.forEach { it(this, cause) }

src/test/kotlin/com/tinder/StateMachineTest.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,27 @@ internal class StateMachineTest {
698698
}
699699
}
700700

701+
class WithMissingStateDefinition {
702+
703+
private val stateMachine = StateMachine.create<String, Int, Nothing> {
704+
initialState(STATE_A)
705+
state(STATE_A) {
706+
on(EVENT_1) {
707+
transitionTo(STATE_B)
708+
}
709+
}
710+
// Missing STATE_B definition.
711+
}
712+
713+
@Test
714+
fun transition_givenMissingDestinationStateDefinition_shouldThrowIllegalStateExceptionWithStateName() {
715+
// Then
716+
assertThatIllegalStateException()
717+
.isThrownBy { stateMachine.transition(EVENT_1) }
718+
.withMessage("Missing definition for state ${STATE_B.javaClass.simpleName}!")
719+
}
720+
}
721+
701722
private companion object {
702723
private const val STATE_A = "a"
703724
private const val STATE_B = "b"

0 commit comments

Comments
 (0)