0

As I need to test publish function parameter passed is correct using Mockk in Kotlin

Below is the code :

   val notificationData = NotificationData(
                notificationId = "test-notificationID",
                operation = "CREATE",
                partnerName = "test-partner",
                created = Instant.now().toEpochMilli().toString(),
                services = []
            )
    verify(exactly = 1) { publish(notificationData) }

But as the created attribute in notificationData object will be having real time value in mock as well as in called function, both are not matching and giving below error

Verification failed: call 1 of 1: publish(eq(NotificationData(notificationId=test-notificationId, partnerName=test-partner, operation=CREATE, mutatedAttributes=null, services=[], created=1633719398360)))). Only one matching call to Notification(object Notification)/publish(NotificationData) happened, but arguments are not matching: [0]: argument: NotificationData(notificationId=test-notificationId, partnerName=test-partner, operation=CREATE, mutatedAttributes=null, services=[], created=1633719398404), matcher: eq(NotificationData(notificationId=test-notificationId, partnerName=test-partner, operation=CREATE, mutatedAttributes=null, services=[], created=1633719398360)), result: -

Anyone please help me to find out, how can I ignore the "created" attribute to get test successful

Mayur Jain
  • 155
  • 1
  • 8

1 Answers1

0

As you were intending to test, it seems you can also mock the created as well. Therefore, instead of using Instant.now().toEpochMilli().toString(), you should put a time milis value to those created, e.g.

val notificationData = NotificationData(
                notificationId = "test-notificationID",
                operation = "CREATE",
                partnerName = "test-partner",
                created = "1633719398404",
                services = []
            )

EDIT

Seems there is another approach that may help, but quite takes effort, by injecting the NotificationData instead in your original class. So, you can mock the NotificationData in your test

Putra Nugraha
  • 574
  • 1
  • 4
  • 12
  • Thanks for your comment, but mocking the created attribute with sample timestamp won't work, as in original function it will be called and that time the attribute will get the real time value and the comparison will get failed. So this won't work. So I am asking is there any way to ignore this attribute to be tested as it value is real time value in "timestamp" – Mayur Jain Oct 11 '21 at 14:30
  • Okay, I have another suggestion, let me update the answer – Putra Nugraha Oct 12 '21 at 02:08
  • 1
    As I had reported this issue to Mockk Git, Below is the link for the solution which worked for me https://github.com/mockk/mockk/issues/720 – Mayur Jain Oct 13 '21 at 13:57