Android中Mockito+JUnit测试Firebase注册方法遇错求助
解决Android单元测试中Firebase注册方法的
Process.myPid not mocked错误 问题根源
你的测试报错核心原因有两个:
- RegisterRepositoryImpl未使用依赖注入的FirebaseAuth实例:在
signUpWithEmailPassword方法中,你直接调用了Firebase.auth(真实的Firebase单例),而非构造函数传入的firebaseAuth参数。这导致测试时触发了真实的Firebase SDK调用,进而调用了Android系统的Process.myPid()方法——本地单元测试环境默认没有实现这类Android系统API,因此抛出异常。 - 测试代码存在冗余逻辑:你重复创建了
mockAuth和repository实例,@Mock注解的repository未被实际使用,测试方法内又重新初始化了对象,导致mock逻辑混乱。
修复步骤
1. 修正RegisterRepositoryImpl代码
修改实现类,确保使用构造函数注入的FirebaseAuth实例,而非直接调用Firebase单例:
package com.example.composetodo.repository import com.example.composetodo.data.RegisterRepository import com.google.firebase.auth.FirebaseAuth class RegisterRepositoryImpl(private val firebaseAuth: FirebaseAuth) : RegisterRepository{ override suspend fun signUpWithEmailPassword(email: String, password: String) { // 使用构造函数传入的firebaseAuth,而非Firebase.auth firebaseAuth.createUserWithEmailAndPassword(email, password) } }
2. 优化测试代码
简化测试逻辑,确保mock的FirebaseAuth被正确使用:
package com.example.composetodo.repository import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.android.gms.tasks.Tasks import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class RegisterRepositoryImplTest { @Mock private lateinit var mockAuth: FirebaseAuth private lateinit var repository: RegisterRepositoryImpl @Before fun setUp() { // 初始化待测试的repository,传入mock的FirebaseAuth repository = RegisterRepositoryImpl(mockAuth) } @Test fun `signUpWithEmailPassword should call firebase auth createUser method`() = runBlocking { val testEmail = "test@example.com" val testPassword = "password_example19038" // Mock FirebaseAuth方法的返回结果 val mockAuthResult = mock(AuthResult::class.java) `when`(mockAuth.createUserWithEmailAndPassword(testEmail, testPassword)) .thenReturn(Tasks.forResult(mockAuthResult)) // 执行待测试方法 repository.signUpWithEmailPassword(testEmail, testPassword) // 验证方法是否被正确调用 verify(mockAuth).createUserWithEmailAndPassword(testEmail, testPassword) } }
3. 可选:配置单元测试默认返回值
如果仍有其他未mock的Android API报错,可以在build.gradle.kts中添加配置,让未mock的方法返回默认值:
android { // ...其他配置项 testOptions { unitTests { isReturnDefaultValues = true } } }
为什么之前的方法无效?
你尝试的Robolectric和isIncludeAndroidResources配置无法解决核心问题——因为代码根本没有使用你mock的FirebaseAuth实例,而是直接调用了真实的Firebase SDK,触发了未被mock的系统API调用。只有修正依赖注入的使用逻辑,才能让mock生效,避免触发真实的Android系统方法。
内容的提问来源于stack exchange,提问作者Mateus Camillo
相关产品推荐
相关产品推荐

