Junit testcase for uniqueId method generator | Community
Skip to main content
Level 3
May 26, 2022
Solved

Junit testcase for uniqueId method generator

  • May 26, 2022
  • 1 reply
  • 617 views

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.
Best answer by arunpatidar

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 

1 reply

arunpatidar
Community Advisor
arunpatidarCommunity AdvisorAccepted solution
Community Advisor
May 27, 2022

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