在同一测试中模拟PendingIntent实例和静态

时间:2017-10-08 00:43:45

标签: android junit mockito robolectric powermockito

我似乎无法弄清楚这一点。我得到java.lang.IncompatibleClassChangeError: Implementing class

我试图弄清楚如何通过将其推入组织类来发送待处理的意图。目前我有以下内容:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PendingIntent.class)
public class TheTests{
    private Context _context;
    private AlarmManager _alarmManager;
    private Manager _manager;

    @Before
    public void setup() {
        _alarmManager = Mockito.mock(AlarmManager.class);
        _context = Mockito.mock(Context.class);
        Mockito.when(_context.getSystemService(anyString())).thenReturn(_alarmManager);
        _manager = new Manager(_context);
    }

    @Test
    public void example() {
        PendingIntent expected = PowerMockito.mock(PendingIntent.class);

        PowerMockito
                .when(PendingIntent.getBroadcast(any(Context.class), anyInt(), any(Intent.class), anyInt()))
                .thenReturn(expected);

        _manager.broadcast(_cal, new Schedule());
    }
}

public Manager class {
    public void broadcast(Thing thing) {
        if (thing == null) {
            return;
        }

        Intent sender = new Intent("broadcast.AlarmReceiverFilter");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, 0, sender, PendingIntent.FLAG_CANCEL_CURRENT);
        _alarm.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
    }
}

在完成所有这些之后,我无法想象如何让它们全部发挥得很好。我的目标是验证getBroadcast内的内容以及Intent本身的内容。

我应采取什么方法?

谢谢, 凯利

更新:在下面说话时建议避免使用powermock,所以我尝试了以下内容:

@Test
public void example2() {
    ShadowApplication shadowApp = shadowOf(RuntimeEnvironment.application);

    _manager = new TimeManager(shadowApp.getApplicationContext());
    _manager.broadcast(new Thing());

    List<Intent> intents = shadowApp.getBroadcastIntents();
    assertEquals(intents.size(), 1); // actual size is 0 (zero)
}

1 个答案:

答案 0 :(得分:1)

我不会在这里使用PowerMock

只需使用:

ShadowApplication shadowApp = shadowOf(RuntimeEnvironment.application);
List<Intent> intents = shadowApp.getBroadcastIntents();

然后在那里找到你的意图。

UPD。对不起,我没注意到你嘲笑AlarmManager。你不应该这样做并使用:

AlarmManager alarmManager = (AlarmManager)RuntimeEnvironment.application.getSystemService(Context.ALARM_SERVICE);
ShadowAlarmManager shadowAlarmManager = shadowOf(alarmManager);
List<ShadowAlarmManager.ScheduledAlarm> alarms = shadowAlarmManager.getScheduledAlarms();