We're moving our project to the Kotlin language. We decided to start from tests but faced with some strange behavior.
Here is our test case:
Service.java
public final class Service {
private final JdbcTemplate jdbcTemplate;
public Service(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public long check() {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM table", Long.class);
}
}
JavaTest.java (works fine)
@RunWith(MockitoJUnitRunner.class)
public final class JavaTest {
@Mock
private JdbcTemplate jdbcTemplate;
@InjectMocks
private Service testSubject;
@Test
public void test() {
//given
when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(1L);
//when
long result = testSubject.check();
//then
assertThat(result, is(1L));
}
}
KotlinTest.kt (not working)
@RunWith(MockitoJUnitRunner::class)
class KotlinTest {
@Mock
private lateinit var jdbcTemplate: JdbcTemplate
@InjectMocks
private lateinit var testSubject: Service
@Test
fun test() {
//given
`when`(jdbcTemplate.queryForObject(anyString(), eq(Long::class.java))).thenReturn(1L)
//when
val result = testSubject.check()
//then
assertThat(result, `is`(1L))
}
}
Kotlin test fails with NullPointerException:
java.lang.NullPointerException
at c.i.Service.check(Service.java:13)
at c.i.KotlinTest.test(KotlinTest.kt:30)
Also, MockitoHint says:
[MockitoHint] KotlinTest.test (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:500)
[MockitoHint] ...args ok? -> at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:500)
Can someone describe what is happening here? I'm quite new to Kotlin and might miss something.
Dependencies version: Kotlin 1.1.3-2, Mockito 2.7.19