Reputation: 21
new to Kotlin here!
I just switched some Java testing code into Kotlin and a specific case of null codes is bugging me for the moment. I am trying to test (in a Kotlin @Test code segment) whether this java function raises the right InvalidParameterException:
void addEventListener(
@NonNull DeviceEventListener listener,
@Nullable CompletionListener completionListener);
So this function is called through Kotlin code (which worked fine before being converted from java to kotlin) like so: Before in Java :
deviceTest.addEventListener(null, testCompletionListener);
waiter.expect(InvalidParameterException.class);
The test worked well without errors.
After the transition to Kotlin, the code becomes unreachable or raises KotlinNullPointerException:
deviceTest!!.addEventListener(null!!, testCompletionListener)
waiter!!.expect(InvalidParameterException::class.java)
I am new to Kotlin and seriously at lost in how to make it work like it did precedently in Java. Any idea?
Thanks for taking the time!
Upvotes: 2
Views: 1764
Reputation: 17691
First, in your example you use @NonNull
, but I assume you meant @NotNull
, as this is the correct annotation Kotlin uses.
Second, I'll assume you take the approach of writing tests in Kotlin, but still using those functions in Java code. Otherwise, if your codebase is in Kotlin only, this test is pointless.
Third, if you try to assign null
to @NotNull
parameter, you should receive IllegalArgumentException
, not InvalidParameterException
Finally, you can make use of platform types to simulate this situation:
// This should be a Java class
public class Nulls {
public static final DeviceEventListener NULL_DEVICE_EVENT_LISTENER = null;
}
// In Kotlin
deviceTest.addEventListener(Nulls.NULL_DEVICE_EVENT_LISTENER, testCompletionListener)
But since Nulls
is a Java class anyway, you may as well just keep the entire test as Java, as was suggested in the comments.
Upvotes: 3