capt.swag
capt.swag

Reputation: 10661

How to unit test a random string generator using Junit?

The question I have is simple and straightforward

Let's say I have this function which returns a random string

fun generateRandomId(): String {
    val randomString = UUID.randomUUID().toString().replace("-", "")
    return randomString
}

And I wanna test the above function using JUnit

@Test
fun generateRandomId() {
    Assertions.assertEquals()
}

Not sure how to assert that the randomly generated String doesn't have any "-".

Upvotes: 0

Views: 5770

Answers (1)

Gustavo Pagani
Gustavo Pagani

Reputation: 6988

assertFalse(generateRandomId().contains("-"))

Previous answer to the original question:

If the function uses another class to generate the random String, then inject that other class in the constructor of your class:

class MyClass(someOtherClass: SomeOtherClass) {


    fun generateRandomId(): String {
        val randomString = someOtherClass.generateRandom()
        return randomString
    }
}

and in your tests you mock SomeOtherClass and all you need to do is to check that whatever SomeOtherClass returns, is returned in your function.

@Test
fun testGenerateRandomId() {
   // given
   val someOtherClassMock: SomeOtherClass = mock() // 1
   val myClass = MyClass(someOtherClassMock) // 2
   val randomString = "randomString"
   whenever(someOtherClassMock.generateRandom()).thenReturn(randomString) // 3

   // when
   val result = myClass.generateRandomId()

   // then
   assertEquals(randomString, result)
}

1 and 3: mock the behaviour of SomeOtherClass with your preferred mocking framework / fake implementation

1 and 2: these lines usually go in the setUp method of your test class


Now if you don't use an external class to generate your random String, you will have to paste your code for further help.

Upvotes: 1

Related Questions