3

This is a Kotlin-Mockk based testcase, where I am trying to get the static class "UUID" to be mocked.

this works when used to get random string but not UUID

mockkStatic(UUID::class) every { UUID.randomUUID().toString() } returnsMany uuidSource

//This is the uuid source 
val uuidSource = listOf(
    UUID.randomUUID().toString(),
    UUID.randomUUID().toString(),
    UUID.randomUUID().toString()
)

In the below case it works

@Test
    fun x1() {
        mockkStatic(UUID::class)
        every { UUID.randomUUID().toString() } returnsMany  uuidSource

        listOf(1, 2, 3). forEach { _ ->
            println(UUID.randomUUID().toString())
        }
    }

//But in the below case it does give error

Unable to make private static long java.util.UUID.parse4Nibbles(java.lang.String,int) accessible: module java.base does not "opens java.util" to unnamed module @2aae9190

@Test fun x1() {
     mockkStatic(UUID::class) every { UUID.randomUUID().toString() } returnsMany         uuidSource
        listOf(1, 2, 3). forEach { _ ->
            println(UUID.randomUUID())
        }
    }

Any solution for the second case to work, or any workaround?

1 Answers1

0

Yes, In first case you are accessing toString() function of randomUUID() so mock it worked. Where in second case you are accessing randomUUID() while mocking randomUUID().toString().

Instead of mocking randomUUID().toString(), mock the randomUUID() itself.

val uuidSource = listOf(
    UUID.fromString("350e8400-e29b-41d4-a716-446655440000"),
    UUID.fromString("450e8400-e29b-41d4-a716-446655440000"),
    UUID.fromString("550e8400-e29b-41d4-a716-446655440000"),
)


@Test fun x1() {
    mockkStatic(UUID::class) 
    every { UUID.randomUUID() } returnsMany uuidSource

    listOf(1, 2, 3).forEach { _ -> println(UUID.randomUUID()) }
}

Here we have to use UUID.fromString() in uuidSource as UUID.randomUUID() return type is UUID.

GokulnathP
  • 692
  • 3
  • 9