Skip to content

Instantly share code, notes, and snippets.

Avatar

Johanne Andersen JohanneA

  • Kambr
  • Amsterdam
View GitHub Profile
View shipment-test-w-dsl.kt
fun getShipmentWithOneBox(): ShipmentBuilder {
return buildShipment {
id = 1L
buildBoxes {
id = 1L
buildProduct {
id = 1L
name = "Pink Fussy Jacket"
}
}
View shipment-test-wo-dsl.kt
fun getShipmentWithOneBox(): Shipment {
return Shipment(
id = 1L,
boxes = listOf(
Box(
id = 1L,
contents = listOf(
Product(id = 1L, name = "Pink Fuzzy Jacket"))
)
)
View nested-override-logic.kt
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)
View override-shipment.kt
fun override(
buildShipment: ShipmentTestBuilder.() -> Unit
): ShipmentTestBuilder {
this.buildShipment()
return this
}
View shipment-builder.kt
fun buildShipment(
buildShipment: ShipmentTestDataBuilder.() -> Unit
): Shipment {
val shipmentBuilder = ShipmentTestDataBuilder()
shipmentBuilder.buildShipment()
return shipmentBuilder.build()
}
class ShipmentTestDataBuilder(
var id: Long = 1L,
var boxes: List<Box> = emptyList()
View dsl-shipment-ex.kt
fun shipmentWithOneBoxWithOneProduct(): Shipment = buildShipment {
id = 1L
buildBox {
id = 1L
buildProduct {
id = 1L
name = "Pink Fuzzy Jacket"
}
}
}.build()
View lambda-w-receiver.kt
// Lambda with receiver
fun buildString (
builderAction: StringBuilder.() -> Unit // Note the location of the parentheses
) : String {
val stringBuilder = StringBuilder()
stringBuilder.builderAction() // This is now a method on the string builder
return stringBuilder.toString()
}
val string = buildString {
append("Hello, ") // Note we no longer need the qualifyer in front
View lambda-wo-receiver.kt
//Lambda without receiver
fun buildString (
builderAction: (StringBuilder) -> Unit
) : String {
val stringBuilder = StringBuilder()
builderAction(stringBuilder)
return stringBuilder.toString()
}
val string = buildString {
it.append("Hello, ") // Note the need for adding 'it' in front
View builder-pattern.kt
fun getShipmentWithOneBox(): Shipment {
return ShipmentBuilder()
.withId(1L)
.withBoxes(
BoxBuilder()
.withId(1L)
.withContents(
ProductBuilder()
.withId(1L)
.withName("Pink Fuzzy Jacket")
@JohanneA
JohanneA / object-mother.kt
Last active Nov 22, 2021
Kotlin Test DSL
View object-mother.kt
fun getShipmentWithOneBox(): Shipment {
return Shipment(
id = 1L,
boxes = listOf(
Box(
id = 1L,
contents = listOf(
Product(id = 1L, name = "Pink Fuzzy Jacket"))
)
)