CoDe
CoDe

Reputation: 11156

How to test FCM push notifications in Android

I'm writing a FCM notification integration & it's working fine. To test component is there a way to mock RemoteMessage object?

By mocking I mean to perform Junit test case. Any suggestion !

Upvotes: 0

Views: 4250

Answers (3)

Alexey
Alexey

Reputation: 7442

Go to your FirebaseMessagingService subclass and set breakpoint on the onMessageReceived method. Send a normal push notification like you normally do. Inspect remoteMessage object while standing on breakpoint. One of the properties of this object would be Bundle. Now, you just need to manually create a Bundle that looks the same and then create RemoteMessage with that bundle, e.g.:

val bundle = Bundle().apply {
    // System fields
    putString("google.delivered_priority", "high")
    putLong("google.sent_time", Date().time)
    putLong("google.ttl", 2419200)
    putString("google.original_priority", "high")
    putString("google.message_id", UUID.randomUUID().toString())
    putString("from", <your fcm project_number, from google-services.json>)

    // Custom fields
    putString("type", "my-type")
    putString("message", "Me message")
    ...
}
val remoteMessage = RemoteMessage(bundle)

Upvotes: 3

Maneki Neko
Maneki Neko

Reputation: 1257

Unfortunately, you can't, and there are no signs of supporting it in the near future.

What you can do: what we did, was to build an API command in your server, that would send you a test push. It would be tedious to support, but that's as good as it gets.

Even worse: suppose that the testing is done to guarantee reliability. What if it fails? You request a new token but FCM will give you the same one, probably... but it does not work! If you invalidate and request a token - will it help? Not sure.

Your options are limited indeed.

Upvotes: 0

AL.
AL.

Reputation: 37798

There is currently no way to mock a RemoteMessage object used in FCM. AFAIK, there isn't even a way to test the onMessageReceived() method without using the actual service.

What is only valid to do is to test your sendNotification() (or whatever you named your method) that hopefully accepts a Hashmap that may come from the RemoteMessage object (this is of course if you're only using a data message payload.

Upvotes: 1

Related Questions