free geoip
45

How to Fix Mockito Null Returned in Kotlin Test

Running unit tests with Mockito in Kotlin can sometimes lead to an annoying and confusing issue: Null returned from a…

Running unit tests with Mockito in Kotlin can sometimes lead to an annoying and confusing issue: Null returned from a Mockito mock. This problem usually happens when using Kotlin’s null-safety features with Java-based mocking libraries like Mockito. In this article, we’ll walk through what causes this error and provide a working solution with full example code using Enlighter for code formatting.

Mockito null returned Kotlin

Understanding the Issue

The error message:

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Returned null instead of a mock

This typically means Mockito couldn’t inject the dependency because the field or method you’re trying to mock is null. Since Kotlin is strict about nullability, this creates a disconnect with Mockito, which defaults to returning null when not instructed otherwise.

Common Causes of the Error

  • Incorrect use of annotations like @Mock, @InjectMocks
  • Mockito not initialized properly with MockitoAnnotations.openMocks(this)
  • Trying to inject a mock into a Kotlin val instead of var
  • Mockito not compatible with Kotlin null-safety without help from plugins like mockito-kotlin

Solution: Using Mockito Properly in Kotlin

Let’s look at how to set up a working example of Mockito test in Kotlin and avoid the “null returned” issue.

Step 1: Add Dependencies

dependencies {
    testImplementation 'org.mockito:mockito-core:5.12.0'
    testImplementation 'org.mockito.kotlin:mockito-kotlin:5.2.1'
    testImplementation 'junit:junit:4.13.2'
}

The key here is the use of mockito-kotlin which provides Kotlin-friendly extensions and avoids null problems.

Step 2: The Code to Test

class UserRepository(private val apiService: ApiService) {
    fun getUserName(userId: String): String {
        val user = apiService.getUser(userId)
        return user.name
    }
}

data class User(val id: String, val name: String)

interface ApiService {
    fun getUser(userId: String): User
}

Step 3: Writing the Unit Test with Mockito

class UserRepositoryTest {

    private lateinit var apiService: ApiService
    private lateinit var userRepository: UserRepository

    @Before
    fun setup() {
        apiService = mock()
        userRepository = UserRepository(apiService)
    }

    @Test
    fun `should return user name`() {
        val dummyUser = User("1", "John Doe")

        whenever(apiService.getUser("1")).thenReturn(dummyUser)

        val result = userRepository.getUserName("1")

        assertEquals("John Doe", result)
    }
}

Important Notes

  • Always use mockito-kotlin’s mock() and whenever() to avoid null-return issues.
  • Don’t use val with @Mock in Kotlin, use var or initialize inside setup().

Alternative with Annotations (Not Recommended in Kotlin)

While possible, annotation-based mock initialization is discouraged in Kotlin due to its strict final and null-safety constraints.

@RunWith(MockitoJUnitRunner::class)
class UserRepositoryTest {

    @Mock
    lateinit var apiService: ApiService

    @InjectMocks
    lateinit var userRepository: UserRepository

    @Test
    fun `should return user name`() {
        val dummyUser = User("1", "John Doe")
        whenever(apiService.getUser("1")).thenReturn(dummyUser)
        val result = userRepository.getUserName("1")
        assertEquals("John Doe", result)
    }
}

Even though the above might work, it may break in future Kotlin versions due to final classes and constructor requirements.

Conclusion

Mockito was built for Java, and while it can be used with Kotlin, you have to be aware of the differences in language behavior. The “Null returned from a mock” error is common, but by using mockito-kotlin and proper test setup, this issue can be avoided entirely. Always test with late initialization, prefer mock() over annotations, and use whenever() from the mockito-kotlin library to ensure your mocks behave correctly.

More Resources

For advanced users, visit Mockito-Kotlin GitHub repository for documentation and usage patterns.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *