Junit testcase for uniqueId method generator | Community
Skip to main content
Level 3
May 26, 2022 1:01 PM UTC
Solved

Junit testcase for uniqueId method generator

Hi All,

Could you please let me know how to write junit for the below method generating randomId in sling model.

public String getRandomId() {

    int n=8;

    byte[] array = new byte[256];

    new Random().nextBytes(array);

 String randomString = new String(array, Charset.forName("UTF-8"));

    StringBuffer r = new StringBuffer();

    for (int k = 0; k < randomString.length(); k++) {

        char ch = randomString.charAt(k);

        if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))&& (n > 0)) {

            r.append(ch);

            n--;

        }

    }

    return "_"+r.toString();

}

 

Thanks in Advance!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
arunpatidar
arunpatidarAccepted solution
New Participant
May 27, 2022 10:37 AM UTC

Hi,

You can mock the output of generated item and have it the same value(have few more test cases with different use cases)

e.g.

https://stackoverflow.com/questions/14811014/writing-a-junit-test-for-a-random-number-generator 

Arun Patidar

1 reply

arunpatidar
arunpatidarAccepted solution
New Participant
May 27, 2022 10:37 AM UTC

Hi,

You can mock the output of generated item and have it the same value(have few more test cases with different use cases)

e.g.

https://stackoverflow.com/questions/14811014/writing-a-junit-test-for-a-random-number-generator 

Translate
Arun Patidar