Use KClass # javaObjectType instead , for example:
// use java.lang.Long rather than long ---v `when`(jdbcTemplate.queryForObject(anyString(), eq(Long::class.javaObjectType))) .thenReturn(1L)
Why is this error occurring?
This is because Long::class.java returns the primitive type long , and not the class java.lang.Long . eg:
println(Long::class.java.name) // long println(Long::class.javaObjectType.name) // java.lang.Long println(Long::class.javaObjectType == Long::class.java) // ^--- false: thier class are different
The mocked parameters subroutine is [String, Class< long >] in the Kotlin test code. when mockito cannot find the associated [String, Class< long >] method for mocking in the Java Service class, then return the default value for the inappropriate getForObject method, but the return type of the getForObject method is Object , so null The value is returned by default.
However, the return type of the check method is long , and the JVM tries to unpack the null primitive type long in your Service class, then a NullPointerException was thrown, for example:
`when`(jdbcTemplate.queryForObject(anyString(), eq(Long::class.java))) .thenReturn(1L) assertEquals(1, jdbcTemplate.queryForObject("<any>", Long::class.java)) // ^--- matched: return 1 assertNull(jdbcTemplate.queryForObject("<any>", Long::class.javaObjectType)) // ^--- mismatched: return null testSubject.check() // ^--- throws NullPointerException
IF you replace Java test code long.class , you also get the same error, for example:
// use long.class rather than Long.class ---v when(jdbcTemplate.queryForObject(anyString(), eq(long.class))).thenReturn(1L); // v--- matched: return 1L assertThat(jdbcTemplate.queryForObject("<any>", long.class), is(1L)); try { // v--- mismatched: return null long value = jdbcTemplate.queryForObject("<any>", Long.class); // ^--- throws NullPointerException when doing unboxing operation fail(); } catch (NullPointerException expected) { assertTrue(true); }