Unit testing a function literal

In my code:

object OrderProcessor extends App{
case class OrderDetail(arrivalTime: Int, duration: Int);

val hasOrderArrived = (timeMark: Long, orderDetail: OrderDetail) => {
orderDetail.arrivalTime <= timeMark
}

}

In test:

test(“OrderProcessor.hasOrderArrived”) {
assert(OrderProcessor.hasOrderArrived(3, OrderDetail(2, 10)) === true)
}

The test gives java.lang.NullPointerException.
If I turn hasOrderArrived into method using ‘def’, test works fine.
How can I test it without this change?

It’s extends App which is to blame. It messes with the initialization of your variables. I would suggest not putting logic which you want to unit test inside something that extends App. It’s like wanting to rip a local variable out of your main method in order to unit test it. You cannot do it. Unfortunately with App it looks like you can do it, until the NullPointerExceptions are slapping you in the face.

2 Likes