Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Junit testcase for uniqueId method generator

Avatar

Level 3

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!

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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 

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

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