使用单元测试测试通知

rek*_*ire 5 notifications android unit-testing

我有一堆带有要自动测试的条件的通知类型。我现在的问题是我知道无法生成通知并检查通知中心中生成的 UI 是否符合预期。

因此,我试图将其分解为调用我的BroadcastReceiver并拦截我触发通知的那个点。所以那时我可以检查通知是否包含我期望的所有设置。我必须希望它会按预期呈现:-)

在我的build.gradle我添加了这个块:

testOptions {
    unitTests.returnDefaultValues = true
}
Run Code Online (Sandbox Code Playgroud)

这里开始我的麻烦,我创建Intent并调用接收器:

@RunWith(MockitoJUnitRunner.class)
public class NotificationTest {
    @Mock
    Context mMockContext;

    @Test
    public void firstTest() {
        NotificationManager manager = new NotificationManager();
        manager.onReceive(mMockContext, new Intent(NotificationManager.MY_ACTION));
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码崩溃了,NullPointerException因为我在我的中有这么好的一行BroadcastReceiver:

switch(intent.getAction()) {
Run Code Online (Sandbox Code Playgroud)

我可以想象这里会发生什么。模拟 API 没有创建一个真实的Intent,我的数据消失了。我现在如何测试我的通知实现?我猜PendingIntent我接下来要测试的s 将不起作用。

我现在能做什么?

rek*_*ire 0

我的解决方案现在是模拟意图,如下所示:

Intent action = spy(new Intent(NotificationManager.MY_ACTION));
doReturn(NotificationManager.MY_ACTION).when(action).getAction();
Run Code Online (Sandbox Code Playgroud)

然而,这只是一种解决方法。后来我遇到了该类在构建器模式中仅返回空值的问题Notification.Builder(),因此这根本无法解决它。