To help with the number generation we can leverage Googles Phone Library. The library is primarily used for parsing numbers and validating them. But they do have a test utility that generates an example number. This example number unfortunately is only one number and can’t be used in a bunch of random tests.
Get library
Resolve the dependency through maven by defining it in your pom.xml.
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.10.9</version>
</dependency>compile group: 'com.googlecode.libphonenumber', name: 'libphonenumber', version: '8.10.9'Library usage
What we will do is generate the example number as a base for our test number. We’ll take that number remove the last 4 digits and replace it with a random 4 digits that will be our test number.
Here is the code:
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
PhoneNumber number = util.getExampleNumberForType(PhoneNumberType.MOBILE);
String exampleNumber = util.format(number, PhoneNumberFormat.RFC3966);
String updatedNumberString = exampleNumber.substring(0, exampleNumber.length()-4);
Random random = new Random();
int lastDigits = random.nextInt(10000);
DecimalFormat df4 = new DecimalFormat("0000"); // 4 zeros
String textPhoneNumber = updatedNumberString + df4.format(lastDigits);The important detail to to make sure you use the DecimalFormat class to make sure that randoms that are 3 can be interpreted as 0003 and randoms over 4 digits will be truncated.
Some references to follow up on:
- (https://stackoverflow.com/q/4574713)
- (https://stackoverflow.com/questions/4574713/generate-random-number-with-restrictions)
- (https://groups.google.com/forum/#!topic/libphonenumber-discuss/rTyhA12dpLE)
If you have some other suggestions, feel free to comment below.