You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Robolectric中NotificationManager.isNotificationPolicyAccessGranted空指针异常排查及测试编写

解决Robolectric测试中NotificationManager.isNotificationPolicyAccessGranted()的空指针异常

我来帮你搞定这个测试里的NPE问题!这种情况通常是因为Robolectric默认的ShadowNotificationManager没有实现isNotificationPolicyAccessGranted()这个方法,调用时会尝试访问未初始化的真实系统服务对象,从而抛出空指针异常。下面给你两种可行的解决方案:

方案一:自定义Shadow类覆盖目标方法

我们可以自己写一个Shadow类,实现isNotificationPolicyAccessGranted()方法,并且提供一个开关来控制返回值,方便不同测试场景使用。

Kotlin版本的自定义Shadow类

@Implements(NotificationManager::class)
class ShadowCustomNotificationManager : ShadowNotificationManager() {
    private var policyAccessGranted = false

    @Implementation
    fun isNotificationPolicyAccessGranted(): Boolean {
        return policyAccessGranted
    }

    // 供测试代码调用,设置权限状态
    fun setNotificationPolicyAccessGranted(granted: Boolean) {
        policyAccessGranted = granted
    }
}

在测试类中使用自定义Shadow

package com.xi_zz.mutephonebutton

import android.app.NotificationManager
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.Shadows.shadowOf
import org.robolectric.RuntimeEnvironment

@RunWith(RobolectricTestRunner::class)
// 指定使用我们自定义的Shadow类
@Config(shadows = [ShadowCustomNotificationManager::class])
class YourTestClass {
    private lateinit var context: Context
    private lateinit var notificationManager: NotificationManager

    @Before
    fun setup() {
        context = RuntimeEnvironment.application
        notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        
        // 获取自定义Shadow实例,设置权限状态(这里根据测试需求设为true或false)
        val shadowManager = shadowOf(notificationManager) as ShadowCustomNotificationManager
        shadowManager.setNotificationPolicyAccessGranted(true)
    }

    @Test
    fun testNotificationPolicyAccess() {
        val isGranted = notificationManager.isNotificationPolicyAccessGranted()
        assertEquals(true, isGranted)
    }
}

方案二:升级Robolectric版本

如果你使用的是较旧的Robolectric版本(比如低于4.3),可以尝试升级到最新稳定版。新版本的Robolectric已经对更多系统服务的API做了实现,可能已经默认支持isNotificationPolicyAccessGranted()方法,不需要自定义Shadow就能正常调用。

小提示

测试时记得根据你的业务逻辑,灵活设置权限的状态(允许/拒绝),这样才能覆盖不同的测试分支哦。

内容的提问来源于stack exchange,提问作者Xi Wei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:41:43