简体   繁体   English

使用单元测试测试通知

[英]Testing notifications with unit tests

I have a bunch of notification types with conditions which I want to test automatically. 我有一堆通知类型,包含我想自动测试的条件。 My problem is now that I know that it is impossible to generate the notification and to check if the generated UI in the notification center looks like expected. 我现在的问题是,我知道无法生成通知并检查通知中心生成的UI是否与预期的一样。

Because of that I tried to break it down to calling my BroadcastReceiver and intercept that point where I fire the notification. 因此,我试图将其分解为调用我的BroadcastReceiver并拦截我触发通知的那一点。 So at that point I can check if the notification contains all settings I expect. 所以在那时我可以检查通知是否包含我期望的所有设置。 I have to hope that it will been rendered as expected :-) 我不得不希望它会按预期呈现:-)

In my build.gradle I added this block: 在我的build.gradle我添加了这个块:

testOptions {
    unitTests.returnDefaultValues = true
}

Here starts my trouble I create the Intent and call the receiver: 这开始我的麻烦我创建了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));
    }
}

This code crashes with a NullPointerException because I have this nice line in my BroadcastReceiver : 这段代码崩溃了NullPointerException因为我在BroadcastReceiver有这条好行:

switch(intent.getAction()) {

I can imagine what happens here. 我可以想象这里发生了什么。 The mocking API does not create a real Intent and my data are gone. 模拟API不会创建真正的Intent ,我的数据也消失了。 How can I test now my notification implementation? 我如何测试我的通知实施? I guess that the PendingIntent s which I want to test next won't work ether. 我想我想要接下来测试的PendingIntent将无法工作。

What can I do now? 我现在能做什么?

My solution is for now to mock the intent as follow: 我现在的解决方案是嘲笑意图如下:

Intent action = spy(new Intent(NotificationManager.MY_ACTION));
doReturn(NotificationManager.MY_ACTION).when(action).getAction();

However this is just a workaround. 然而,这只是一种解决方法。 Later I run into the issue that the Notification.Builder() class returns just nulls in the builder pattern so this won't fix it at all. 后来我遇到了Notification.Builder()类在构建器模式中返回null的问题,所以这根本不会修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM