Skip to content

Instantly share code, notes, and snippets.

@JohanneA
Last active November 22, 2021 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohanneA/29fbce36b7950496479c3819ac902967 to your computer and use it in GitHub Desktop.
Save JohanneA/29fbce36b7950496479c3819ac902967 to your computer and use it in GitHub Desktop.
Kotlin test DSL
inline fun overrideBox(
id: Long,
buildBox: BoxTestDataBuilder.() -> Unit
) {
if (!boxIdExists(id)) {
throw IllegalArgumentException("Box with id $id does not exist")
}
val boxBuilder = BoxTestDataBuilder()
val existingBox = getBox(id)
boxBuilder.merge(existingBox)
boxBuilder.buildBox()
removeBoxes(id)
addBox(boxBuilder.build())
}
fun boxIdExists(boxId: Long): Boolean {
return this.boxes.find { it.id == boxId } != null
}
fun getBox(boxId: Long): Box {
return this.boxes.find { it.id == boxId }!!
}
fun removeBox(boxId: Long) {
val mutableBoxes = this.boxes.toMutableList()
mutableBoxes.removeIf { it.id == boxId }
this.boxes = mutableBoxes.toList()
}
// Merge function inside the box test data builder
class BoxTestDataBuilder(
var id: Long = 1L,
var contents: List<Product> = emptyList()
) {
//...
fun merge(box: Box): BoxTestDataBuilder {
this.id = box.id
this.contents = box.contents
return this
}
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment