Search code examples
androidmockitoandroid-junitmockito-kotlin

Android: Mocking GoogleSignIn.getClient is resulting in Null Pointer Exception


Trying to mock static object GoogleSignIn.getClient() method but getting this error from the initialize() method:

getClient(context, gso) must not be null java.lang.NullPointerException: getClient(context, gso) must not be null

Here is the class under test

package com.example.hellogooglesignin

import android.content.Context
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions

data class UserAccount(val context: Context) {
    private lateinit var googleSignInClient: GoogleSignInClient

    fun initialize() {
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build()
        googleSignInClient = GoogleSignIn.getClient(context, gso)
    }
}

And the unit test code

package com.example.hellogooglesignin

import android.content.Context
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mock
import org.mockito.Mockito

class GoogleSignInTest {
    @Mock
    private lateinit var googleSignInClient: GoogleSignInClient
    @Mock
    private lateinit var context: Context

    @Before
    fun setup() {
        googleSignInClient = Mockito.mock(GoogleSignInClient::class.java)
        context = Mockito.mock(Context::class.java)
    }

    @Test
    fun testInitialize() {
        Mockito.mockStatic(GoogleSignIn::class.java).use { ms ->
            ms.`when`<GoogleSignInClient> { GoogleSignIn.getClient(any(), any()) }.thenReturn(googleSignInClient)

            val account = UserAccount(context)
            account.initialize()
            assertEquals(1, 1)
        }
    }
}

Returned mock object for GoogleSignInClient is not null:

enter image description here

Any idea?

Using:

    implementation 'com.google.android.gms:play-services-auth:20.5.0'

    testImplementation 'junit:junit:4.13.2'
    testImplementation 'org.mockito:mockito-core:4.5.1'
    testImplementation 'org.mockito:mockito-inline:3.5.6'

Solution

  • Solved by replacing

    GoogleSignIn.getClient(any(), any())

    with

    GoogleSignIn.getClient(any(Context::class.java), any(GoogleSignInOptions::class.java)).