I have code that looks like this, to detect an NPE in an assignment. The assignment triggers an implicit conversion in which the NPE happens (it implicitly converts from a CoreRecommendedDomain to an APIRecommededDomain:
"ensure Scala RecommendedDomain from null must throw NPE" in {
val n: CoreRecommendedDomain = null
var r: APIRecommendedDomain = APIRecommendedDomain("example.com")
(r = n) must throwA[NullPointerException]
}
The above code works. But, of course, I'd rather not have to create a dummy APIRecommendedDomain into a var only to test assignment. I'd much rather detect the NPE when I do something like:
val r: APIRecommendedDomain = n
I can't seem to find how to do this short of wrapping the whole thing in a try/catch. That kinda defeats the more elegant syntax, though.
Or am I out of luck?
You can assign a type to null
directly, this should trigger the implicit conversion:
"ensure Scala RecommendedDomain from null must throw NPE" in {
((null: CoreRecommendedDomain): APIRecommendedDomain) must throwA[NullPointerException]
}