简体   繁体   中英

how to write unit test for this class in JUnit

//how to write unit test for this class in JUnit......

package com.emr.common.helper;

import java.util.Random;

public class RandomTextGenerator {

    public static String getAutogenerateText()
    {
        /*Auto genarate password    */

        String password = "";
        /* Create Auto Password */
        int count = 36;
        // int range = Integer.MAX_VALUE;
        int sum = 0;

        Random rand = new Random();
        for (int j = 0; j < 45; j++) {
            for (int i = 0; i < count; i++) {
                sum = rand.nextInt(count);

            }
            char[] pass = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                    'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9' };
            password = password + pass[sum];
        }

        return password;
    }

}

You won't be able to effectively test this class if you say new Random() - by doing this you have hard-coded a reference to what is effectively an external dependency (a source of random numbers) which you can't control.

Instead you should pass a Random object into the class via a method argument, and supply a mock implementation in your test for which you can control the values that get returned.

Try to match it against an RegEx which checks if the returned String matches 45 characters mixed of Letters and Digits.

This RegEx should work:

^[A-Z0-9]{45}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM