April 12, 2019

Generating Test Data - JavaFaker

JavaFaker is good library for generating localized faked test data.


<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>0.17.2</version>
    <scope>test</scope>
</dependency>

Faker faker = new Faker(new Locale("sv-SE")); // default Locale("en", "")

faker.name().name()         // optional prefix, a firstname and a lastname
faker.name().nameWithMiddle()   // optional prefix, a given and family name, another 
                                // 'firstname' for the middle name and 
                                // an optional suffix such as Jr. 
faker.name().title()
faker.name().prefix()       // e.g. Mr., Mrs., Ms.
faker.name().firstName()
faker.name().lastName()
faker.name().suffix()       // e.g. Jr., Sr., I, II
// and more username, fullName, ...

faker.address().streetAddress()
faker.address().secondaryAddress()
faker.address().zipCode()
faker.address().city()
// and more city, state, county, country, ...

faker.number().numberBetween(0, 99999999999999L)
faker.number().randomDigitNotZero()
// and some more double randomDouble, long randomNumber(), ...

faker.date().between(from, to)
// and more past, future, ...

faker.idNumber().validSvSeSsn(); // swedish social security number in format "######-####", "######+####"

And if that is not enough, you create custom


FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService());
fakeValuesService.regexify("[a-z1-9]{10}");
fakeValuesService.letterify("12??34", boolean isUpper)  // Returns a string with the '?' characters 
                                                        // in the parameter replaced with random 
                                                        // alphabeticcharacters.

// numberify - Returns a string with the '#' characters in the parameter 
// replaced with random digits between 0-9 inclusive.

// bothify(String string, boolean isUpper) - applies both a numerify(String) and a letterify(String, boolean)

See also https://www.baeldung.com/java-faker.

No comments: