Skip to content

MockNeat

Andrei Ciobanu edited this page Jan 10, 2019 · 44 revisions

Important Note: The library the documentation has moved to www.mockneat.com. The information found on this wiki is quite outdated. Please check the new site.


The MockNeat class

The MockNeat is composed by a set of objects that help us generate arbitrary data.

Each of those objects is an implementation of the interface MockUnit<T> which is described in great detail in the next section.

The most important methods that can be accessed on the MockNeat object are:

Method Returning Type Description
bools() Bools The Bools class implements MockUnit<Boolean>. It is used to generate arbitrary Boolean values.
chars() Chars The Chars class implements MockUnit<Character>. It is used to generate arbitrary character values (letters, digits, special characters, etc.).
cities() Cities The Cities class implements MockUnit<String>. It is used to generate arbitrary city names.
constructor() Constructor The Constructor class implements MockUnit<T>. It is used to generate / mock objects by calling constructors.
countries() Countries The Countries class implements MockUnitString. It is used to generate country names or their corresponding ISO2 code.
creditCards() CreditCards The CreditCards class implements MockUnitString. It is used to generate valid Credit Card Numbers (numbers that pass the Luhn Check). Using creditCards().names() it is possible to generate Credit Card names as Strings.
currencies() Currencies This is a helper class that groups different methods related to currencies: currencies().name(), currencies().symbol(), currencies().code(), currencies().forexPair()
csvs() CSVs The CSVs class implements MockUnitString. It is used to generate CSV files (or text) from other MockUnit<T>.
cvvs() CVVs The CVVs class implements MockUnitString. It is used to generate CVV codes for Credit Cards (3 or 4 digit numbers).
days() Days This Days class implements MockUnitDays. It is used to generate days of the week.
dicts() Dicts The Dicts class is used as a an utility class that facilitates generating random lines from the internal library dictionaries. The internal dictionaries are collections of data grouped into files. The enum DictType maps all those files.
departments() Departments The Departments class implements MockUnitString. It is used to generate arbitrary department names from company.
domains() Domains The Domains class implements MockUnitString. It is used to generate web domains like 'com', 'net', 'org' and so on.
doubles() Doubles The Doubles class implements MockUnitDouble. It is used to generate double numbers.
emails() Emails The Emails class implements MockUnitString. It is used to generate emails.
factory() Factory The Factory class implements MockUnit<T>. It is used to generate mock instances using static factory methods.
files() Files The Files class implements MockUnitString. It is used to read random lines from "external" files that are loaded in memory.
filler() Filler The Filler class implements MockUnit<T>. It is used to generate mock instances using Supplier<T> instead of reflection.
floats() Floats The Floats class implements MockUnit<Float>. It is used to generate float numbers.
fmt() Formatter The Formatter class implements MockUnitString. It is used to generate formatted Strings.
from() MockUnit<T> This method is used to return random values from a List<T>, T[] and Class<T extends Enum<?>>.
fromKeys() MockUnit<T> This method is used to return a random key from a Map<T, ?>.
fromValues() MockUnit<T> This method is used to return a random value from a Map<T, ?>.
genders() Genders This class implements MockUnitString. It is used to generate ("M", "F") or ("Male", "Female") values.
hashes() Hashes This is a helper method that groups the following methods for generating hex hashes using different algorithms: hashes().md2(), hashes().md5(), hashes().sha1(), hashes().sha256(), hashes().sha384(), hashes().sha512().
ibans() IBANs The IBANs class implements MockUnitString. It is used to generate arbitrary IBAN strings that have a correct check digit. The implementation is quite naive because it doesn't take in consideration National Bank Code, Balance Account Number, Branch Code, etc.`
ints() Ints The Ints class implements MockUnitInt. It used to generate integer numbers.
intSeq() IntSeq The IntSeq class implements MockUnitInt. It used to generate integer numbers in a sequence.
ipv4s() IPv4s The IPv4s class implements MockUnitString. It is used to generate arbitrary IPv4 addresses.
ipv6s() IPv6s The IPv6s class implements MockUnitString. It is used to generate arbitrary IPv6 addresses.
issns() ISSNS The 'ISSNSclass implementsMockUnitString`. It is used to generate arbitrary ISSN codes.
localDates() LocalDates The LocalDates class implements MockUnitLocalDate. It is used to generate random date objects.
longs() Longs The Longs class implements MockUnitLong. It is used to generate random long numbers.
longSeq() LongSeq The LongSeq class implements MockUnitLong. It is used to generate long numbers in a sequence.
macs() Macs The Macs class implements MockUnitString. It is used to generate MAC addresses.
markovs() Markovs The Markovs class implements MockUnitString. It is used to generate Markov Text.
mimes() 'Mimes' The 'Mimes' class implements MockUnitString. It is used to generate mime types.
months() Months The Months class implements MockUnitMonth. It is used to generate month names.
money() Money The Money class implements MockUnitString. It used to generate random sums of money for a certain Locale.
names() Names The Names class implements MockUnitString. It is used to generate random names.
naughtyStrings() NaughtyStrings The NaughtyStrings class implements MockUnitString. It is used to generate naughty strings - strings that have a high probability of creating "problems" when used as user input. This module was implemented using: https://github.com/minimaxir/big-list-of-naughty-strings as a reference.
passwords() Passwords The Passwords class implements MockUnitString. It is used to generate random passwords.
probabilities() Probabilities The Probabilities class implements MockUnit<T>. It is used to generate arbitrary values based on probabilities.
reflect() Reflect The Reflect class implements MockUnit<T>. It is used to generate mock objects through reflection.
regex() Regex The Regex class implements MockUnitString. It is used to generate a random string that matches a given regex.
seq() Seq<T> The Seq<T> class implements MockUnit<T>. It is used to cycle through an existing pre-defined dictionary or an Iterable<T>.
sqlInserts() SQLInserts The SQLInserts class implements MockUnit<SQLInsert>. It used to generate arbitrary SQL Inserts.
shufflers() Shufflers This Shufflers is a class that contains useful methods to create new arrays and lists that are shuffled version of a "source" one
sscs() SSCs The SSCs class implements MockUnitString. It is used to generate US Social Security Numbers.
strings() Strings The Strings class implements MockUnitString. It is used to generate random strings.
urls() URLs The URLs class implements MockUnitString. It is used to generate arbitrary URL values.
uuids() UUIDs The UIDs class implements MockUnitString. It is used to generate unique identifiers.
users() Users The Users class implements MockUnitString. It is used to generate random usernames.
usStates() UsStates The UsStates class implements MockUnitString. It is used to generate Us States names or their ISO2 codes.
words() Words The Words class implements MockUnitString. It used to generate random English (for the moment) words. Additional methods that can narrow down the type of word generated words().adjectives(), words().adverbs(), words().nouns(), words().verbs()

bools()

This method help us generate Boolean values.

Example:

MockNeat m = MockNeat.threadLocal();
boolean b = m.bools().val();

Example for generating a boolean value that has 99.99% of being true:

boolean almostAlwaysTrue = m.bools().probability(99.99).val();

chars()

This method helps us generate Character values.

Example for generating alpha numeric characters:

char an = m.chars().alphaNumeric().val();

Example for generating a digit (eg: '1', '2', ... , '0'):

Character digit = mock.chars().digits().val();

Example for generating a lower letter (eg: 'a', 'b', ..., 'z'):

Character lowerLetter = mock.chars().lowerLetters().val();

Example for generating an upper letter (eg.: 'A', 'B', ... , 'Z'):

Character upperLetter = mock.chars().upperLetters().val();

Example for generating a hex value:

Character hex = mock.chars().hex().val();

Example for generating a character from an "alphabet" of characters:

char aOrBorC = m.chars().from(new char[]{'a', 'b', 'c'}).val();
char xOrYorZ = m.chars().from("xyz").val();

cities()

This method helps us generate arbitrary city names:

// Generate a city in the us
String city = mockNeat.cities().us().val();
System.out.println(city);

// Generate a world capital
String worldCapital = mockNeat.cities().capitals().val();
System.out.println(worldCapital);

constructor()

This method is used to generate / mock objects by calling the constructor of the target class (using reflection). The params supplied to the constructor can be MockUnit objects or constants.

The method signature is: <T> Constructor<T> constructor(Class<T> cls).

Example for generating Test mock objects:

public class Test {
    private String x;
    private Integer y;
    private Boolean z;

    public Test() {}
    
    // This is the constructor that is going to be called
    public Test(String x, Integer y, Boolean z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
//...
Test t2 = mock.constructor(Test.class)
              .params(
                 mock.strings().size(10),
                 mock.ints().range(0, 10),
                 true // constant here
              )
              .val();
// Possible Output: Test{x='g4bk67PxlT', y=185, z=false}

countries()

This method help us generate Country names (eg.: "Romania", "Israel", "France") or ISO2 codes for countries (eg.: "RO").

Example for generating a country name:

String countryName = m.countries().names().val();
// Possible Output: Lithuania

Example for generating a country iso2() code.

String iso2 = m.countries().iso2().val()
// Possible Output: MR

creditCards()

This method help us generate Credit Cards.

All the supported credit cards types are defined in the CreditCardType enum.

Example for generating a valid credit card number (by default the CreditCardType is AMERICAN_EXPRESS):

String amex = m.creditCards().val()

Example for generating a 16 digits VISA:

String visa16 = m.creditCards().type(VISA_16).val();

Example for generating an arbitrary credit card that can be either VISA_16 or MASTERCARD.

String visaOrMastercard = m.creditCards()
                           .types(VISA_16, MASTERCARD)
                           .val();

Visa, MasterCard and AMEX credit cards have shortcut methods that can be invoked directly without using type() or types().

String amex = mockNeat.creditCards().amex().val();
String visa = mockNeat.creditCards().visa().val();
String masterCard = mockNeat.creditCards().masterCard().val();

creditCards().names()

This generates the name of a Credit Card.

The possible returning values are: "American Express", "China Union Pay", "Diners Club", "Discover", "Inter Payment", "Insta Payment", "JCB", "Maestro", "Mastercard", "Visa".

Example:

String ccName = m.creditCards().names().val();

currencies()

This method is only used to create an instance of the Currencies object.

The most important methods attached to the Currencies object are:

currencies().name()

This method returns currency names from around the world. Some of the possible outputs: "Leu", "Krona", "Pound", etc.

Example:

String currencyName = mock.currencies().name().val()

currencies().symbol()

This method returns currency symbols from around the world. Some of the possible outputs: "Lek", "£", "Ls", "$", etc.

Example:

String currencySymbol = mock.currencies().symbol().val()

currencies().code()

This method returns currency codes from around the world. Some of the possible outputs: "CZK", "JPY", "SVC", "ANG", etc.

Example:

String currencyCode = mock.currencies().code().val();

currencies().forexPair()

This method returns the most common Forex Pairs. Some of the possible outputs: "EUR/GBP", "USD/ZAR", "EUR/GBP", "EUR/HUF", etc.

Example:

String forexPair = mock.currencies().forexPair().val();

csvs()

The method is used to generate csv files from other MockUnit<T>s.

Example for generating a simple "csv" line:

MockNeat M = ...
String csvLine = M.csvs().column(M.intSeq())
                                 .column(M.names().first())
                                 .column(M.names().last())
                                 .column(M.emails())
                                 .column(M.money().locale(Locale.GERMANY).range(1000, 5000))
                                 .separator("|")
                                 .val();
// Possible Output:
// 0|Dortha|Cayouette|passedbartucca@hotmail.com|"4.215,92 €"

Example for generating multiple .csv lines and store them in a String:

String csvLine = M.csvs().column(M.intSeq())
                         .column(M.names().first())
                         .column(M.names().last())
                         .column(M.emails())
                         .column(M.money().locale(Locale.GERMANY).range(1000, 5000))
                         .separator("|")
                         .accumulate(20, "\n")
                         .val();

System.out.println(csvLine);

//Possible Output:
0|Hal|Gannett|grouserefugio@live.com|"2.907,94 €"
1|Ricardo|Kirsch|thankfuldolan@gmail.com|"3.123,97 €"
2|Nolan|Inglis|webbedjustina@yahoo.co.uk|"3.418,80 €"
3|Sonny|Pareja|wrothjuliana@hotmail.com|"1.041,76 €"
4|Roscoe|Matuszak|snubkeisha@mail.com|"1.645,30 €"
5|Gaston|Hammill|fraughtbruno@hotmail.com|"3.645,93 €"
6|Deshawn|Majercin|fireproofmacqueen@hotmail.com|"4.944,91 €"
7|Jamel|Brodnax|chastekauder@comcast.net|"4.914,91 €"
8|Elliott|Peron|chirkemerita@email.com|"4.604,48 €"
9|Lance|Latina|voguemoths@mac.com|"2.662,07 €"
10|Travis|Rusert|rushdemetrice@att.net|"3.387,07 €"
11|Norris|Amadio|squintfelicia@email.com|"3.889,18 €"
12|Elisha|Brawley|nextwilber@mail.com|"2.522,31 €"
13|Barton|Bosko|pouchedfrederick@mac.com|"2.433,39 €"
14|Herschel|Dotstry|slumsade@yahoo.co.uk|"4.930,66 €"
15|Ashley|Dorenfeld|sorecarlo@comcast.net|"2.734,22 €"
16|Eric|Cheli|kraalchristi@me.com|"3.498,07 €"
17|Norberto|Arechiga|milledstupes@comcast.net|"3.908,81 €"
18|Marco|Berenguer|seenausiello@verizon.net|"3.280,29 €"
19|Douglas|Kerley|boullemerilyn@mail.com|"2.609,39 €"

Example for writing a .csv file on the disk:

M.csvs().column(M.intSeq())
        .column(M.names().first())
        .column(M.names().last())
        .column(M.emails())
        .column(M.money().locale(Locale.GERMANY).range(1000, 5000))
        .separator("|")
        .write("test.csv", 100);

cvvs()

This method helps us generate CVV codes. Currently it supports only two types of CVV. Those types are defined into the enum called CVVType. For the moment there are only two types defined:

  • CVV3 - Represents a 3 digits random String.
  • CVV4 - Represents a 4 digits random String.

By default the type we use is: CVV3.

Example for generating a 3-digit CVV:

String cvv = mock.cvvs().val();

Example for generating a 4-digit CVV:

String cvv4 = mock.cvvs().type(CVV4).val();

dicts()

The library includes a set of internal dictionaries.

The dictionaries are plain-text files that are included in the .jar file.

Each of these files are mapped through an enum called DictType.

The current list of DictType is:

Enum Value Contents
COUNTRY_NAME Contains an exhaustive list of country names. Possible values: "Chile", "Saudi Arabia", etc.
COUNTRY_ISO_CODE_2 Contains an exhaustive list of country iso codes. Possible values: "AM", "UK", etc.
DOMAIN_EMAIL Contains a list of possible email domains. This dictionary is used internally by emails(). Possible values: "gmail.com", "msn.com", etc.
DOMAIN_TOP_LEVEL_ALL Contains an exhaustive list of possible URL domains (suffixes). This dictionary is used internally by urls(). Possible values: "com", "comcast", "ml", etc.
DOMAIN_TOP_LEVEL_POPULAR Contains a list of the most popular URL domains (suffixes). This dictionary is used internally by urls(). Possible values: "com", "org", "net", etc.
FOREX_PAIRS Contains a list of the most popular Forex Currency Pairs. This dictionary is used internally by currencies().forexPair(). Possible values: "USD/MXN", "USD/NOK", "USD/PLN", etc.
CREDIT_CARD_NAMES Contains a list of the most popular credit card names. This dictionary is used internally by creditCards().names(). Possible values: "Visa", "Mastercard", etc.
FIRST_NAME_MALE_AMERICAN Contains the most common first names for males in the US.
FIRST_NAME_FEMALE_AMERICAN Contains the most common first names for females in the US.
LAST_NAME_AMERICAN Contains the most common last names in the US.
EN_ADJECTIVE_1SYLL Contains a list of 1-Syllable English adjectives.
EN_ADJECTIVE_2SYLL Contains a list of 2-Syllable English adjectives.
EN_ADJECTIVE_3SYLL Contains a list of 3-Syllable English adjectives.
EN_ADJECTIVE_4SYLL Contains a list of 4-Syllable English adjectives.
EN_ADVERB_1SYLL Contains a list of 1-Syllable English adverbs.
EN_ADVERB_2SYLL Contains a list of 2-Syllable English adverbs.
EN_ADVERB_3SYLL Contains a list of 3-Syllable English adverbs.
EN_ADVERB_4SYLL Contains a list of 4-Syllable English adverbs.
DEPARTMENTS Contains a list of possible department names from a company. Possible values: "Insurance", "Inventory", "Licenses"

Example for generating a country name directly from the dictionary:

String countryName = mock.dicts().type(COUNTRY_NAME).val()

Obtaining all the data from the dictionaries in a (immutable) list can be done through the data() method:

List<String> cIso2 = MockNeat.threadLocal().dicts().data(DictType.COUNTRY_ISO_CODE_2);

days()

This method helps us generate name of the Days of the week.

Example for generating an arbitrary day of the week:

DayOfWeek day = mock.days().val();
// Possible Output: SUNDAY

Example for generating an arbitrary day of the week as String using display():

String dayStr = mock.days().display(TextStyle.SHORT).val();
// Possible Output: "Tue"

Example for generating an arbitrary day of week after "Thursday" using after():

DayOfWeek dayAfterThursday = mock.days().after(THURSDAY).val();
// Possible Output: "FRIDAY"

Example for generating an arbitrary day of the week before "Thursday" using before:

DayOfWeek dayBeforeThursday = mock.days().before(THURSDAY).val();
// Possible Output: "MONDAY"

Example for generating an arbitrary day of the week between [Sunday, Saturday] using rangeClosed():

DayOfWeek weekEnd = mock.days().rangeClosed(SATURDAY, SUNDAY).val();

Note: There is also the range() method, that uses an open interval.

departments()

This method is used to generate department names from a company.

String dept = mock.departments().val();
// Possible Output: "Insurance"

domains()

This method is used to generate domains suffixes for URLs.

There are two types of domain suffixes that can be generated:

  • DomainSuffixType.ALL - This contains an exhaustive list of domain suffixes;
  • DomainSuffixType.POPULAR - This is a shorter list of domain suffixes (the most popular ones): "com", "net", "org", etc. If not type is specified this is picked by default.

Example for generating a domain suffix String:

String domain = mock.domains().val();
// Possible Output: "io"

Example for generating a domain suffix String giving the type:

String all = mock.domains().type(ALL).val();
// Possible Output: "analytics"

doubles()

This method is used to generate double values.

Example for generating a single double value in the interval [0.0, 1.0):

Double val = mock.doubles().val();
// Possible Output: 0.26378031782078615

Example for generating a single double value in interval [0.0, bound)

Double bound = 10.0;
Double boundedVal = mock.doubles().bound(bound).val();
// Possible Output: 7.9842438463207905

Example for generating a single double value in a given range [100.0, 200.0)

Double valInRange = mock.doubles().range(100.0, 200.0).val();
// Possible Output: 194.88613464097585

emails()

This method is used to generate emails.

Example for generating a random email address:

String email = mock.emails().val();
// Possible Output: icedvida@yahoo.com

Example for generating a random email with a fixed "domain". This is useful when generating emails for a specific "company".

String corpEmail = mock.emails().domain("startup.io").val();
// Possible Output: tiptoplunge@startup.io

Example for generating an email with fixed "domains":

String domsEmail = mock.emails().domains("abc.com", "corp.org").val();
// Possible Output: funjulius@corp.org

factory()

This method is used to generate mock objects using static factory methods.

Example:

Test.java class:

public class Test {
    private String x;
    private Integer y;
    private Boolean z;

    public Test() {}

    public Test(String x, Integer y, Boolean z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
//....

TestFactory.class is a class that contains static methods used to create Test instances.

public class TestFactory {
    public static Test buildTest(String x, Integer y, Boolean z) {
        return new Test(x, y, z);
    }
// ..,

The buildTest method can be used to instantiate mock Test objects like this:

Test t3 = mock.factory(Test.class, TestFactory.class)
              .method("buildTest")
              .params(mock.strings(), 1, true)
              .val();
// Possible Output: Test{x='6pmmWFiAEPW35dUj9sjcnOaglfXO7hIoyu38UK395pZ8Ns1dPJSkpz0Sg0C4IVVA', y=1, z=true}

files()

This method is useful to generate random lines from a given file. The file is loaded in memory only once, so the recommendation is to avoid keeping large files into memory.

Example to generate a random line from a file '/Users/nomemory/Desktop/test.txt'. The file contents are:

text1
text2
text3
text4
String line = mock.files().from("/Users/andreinicolinciobanu/Desktop/test.txt").val();
// Possible Output: text2

filler()

The Filler class implements MockUnit<T>. It is used to generate mock instances using Supplier<T> instead of reflection.

List<User> users = m.filler(() -> new User())
                    .setter(User::setUserName,m.users())
                    .setter(User::setFirstName, m.names().first())
                    .setter(User::setLastName, m.names().last())
                    .setter(User::setCreated, m.localDates().thisYear().toUtilDate())
                    .setter(User::setModified, m.localDates().thisMonth().toUtilDate())
                    .list(() -> new ArrayList<>(), 10) // Collecting all the results ina  List of 10 elements.
                    .val();

floats()

This method is used to generate float numbers.

Example to generate a single float value in the interval [0.0f, 1.0f):

Float val = mock.floats().val();
// Possible Output: 0.414554

Example to generate a single float value in interval [0.0f, bound), where bound=10.0f:

Float boundVal = mock.floats().bound(10f).val();
// Possible Output: 2.0780544

Example to generate a single double value in a given range [100.0f, 200.0f)

Float rangeVal = mock.floats().range(100.0f, 200.0f).val();
// Possible Output: 163.93002

fmt()

This method is used to generate formatted String values. Each specified param is a named one #{param1}.

Example for generating a random string in the form: #{digit1}#{digit2}#{letter}#{specialChar} (eg.: "12a@"):

String temp = "{#{d1}#{d2}#{l1}#{sc}";
String result = mock.fmt(templ)
                    .param("d1", mock.chars().digits())
                    .param("d2", mock.chars().digits())
                    .param("l1", mock.chars().letters())
                    .param("sc", mock.from(SPECIAL_CHARACTERS))
                    .val();
// Possible Output: 45q'

from()

This method is used to return a random value from a pre-existing List<T>, T[] or Class<T extends Enum<?>>. The method directly returns a MockUnit<T>.

Example for obtaining a random value from a List:

List<Double> list = asList(0.0, 0.1, 0.5, 0.6);
Double x = m.from(list).val();
// Possible Output: 0.5

Note: If the List is implemented as an ArrayList the complexity of the algorithm will be O(1). If it's a LinkedList the complexity will be O(n).

Example for obtaining a random value from a String[]:

String[] arr = {"abc", "acd", "adf" };
String s = m.from(arr).val();
// Possible Output: "adf"

Example for obtaining a random value from an Enum:

DayOfWeek d = m.from(DayOfWeek.class).val();
// Possible Output: d

fromKeys()

This method is used to return a random key from a Map. The keys of the map are copied internally into an array, and afterwards the next key is randomly picked from there.

The copying of the key elements is an expensive operation so it's not recommended to use this method, especially for large Maps.

fromValues()

This method is used to return a random value from a Map. The values of the map are copied internally into an array, and afterwards the next value is randomly picked from there.

The copying of the value elements is an expensive operation so it's not recommended to use this method, especially for large Maps.

hashes()

This is a helper method that groups the following methods for generating hex hashes using different algorithms:

genders()

This Gender class implements MockUnitString. It is used to generate ("Male", "Female") values:

String gender = mock.genders().val();
// Possible Output: "Female"

Or shortcut letters:

String shortGender = mock.genders().letter().val();
// Possible Output: "M"

hashes().md2()

This method generates a MD2 Hash from a random String:

String str = mock.hashes().md2().val();

hashes().md5()

This method generates a MD5 Hash from a random String:

String str = mock.hashes().md5().val();

hashes().sha1()

This method generates a SHA1 Hash from a random String:

String str = mock.hashes().sha1().val();

hashes().sha256()

This method generates a SHA256 Hash from a random String:

String str = mock.hashes().sha256().val();

hashes().sha384()

This method generates a SHA384 Hash from a random String:

String str = mock.hashes().sha384().val();

hashes().sha512()

This method generates a SHA512 Hash from a random String:

String str = mock.hashes().sha512().val();

ibans()

This method is used to generate possible IBAN codes. The implementation is quite naive because it doesn't take in consideration information like Branch Code Number, Account Number, National Bank Code, etc.

It only matches the country's prefix, character configuration as defined in the standard, plus the correct length.

String iban = mock.ibans().type(GERMANY).val();

ints()

This method is used to generate int numbers.

Example for generating int numbers (negative or positive):

Integer i1 = mock.ints().val();
// Possible Output :1952620297

Example for generating int numbers bounded by a certain value: [0, bound), where bound = 10:

Integer bounded = mock.ints().bound(10).val();
// Possible Output: 4

Example for generating int numbers in a certain open range: [10, 20):

Integer ranged = mock.ints().range(10, 20).val();
// Possible Output: 19

intSeq()

This method is used to generate sequence of numbers (integers).

Example for generating a sequence of integers starting with 0, incrementing each time with 1.

IntSeq seq = mock.intSeq();
for(int i = 0; i < 20; i++) {
      System.out.print(seq.val() + " ");
}
// Output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

Example for generating a sequence of integers starting with 5, incrementing with 2, and if it reaches a value bigger than 20 it resets back to 5:

IntSeq seq2 = mock.intSeq()
                  .start(5)
                  .increment(2)
                  .max(20)
                  .cycle(true);
for(int i = 0; i < 50; i++) {
    System.out.print(seq2.val() + " ");
}
// Output: 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 

Negative increments work, but instead of setting a max() value a min() needs to be set, otherwise it will default to Integer.MIN_VALUE.

ipv4s()

This method is used to generate arbitrary IPv4 addresses.

An enum IPv4Type exists and it describes each possible IPv4 classes: CLASS_A, CLASS_A_LOOPBACK, CLASS_A_PRIVATE, CLASS_B, CLASS_B_PRIVATE, CLASS_C, CLASS_C_PRIVATE, CLASS_D, CLASS_E, NO_CONSTRAINT.

Example for generating an IPv4 address that has no class constraint:

String ipv4 = mock.ipv4s().val();
// Possible Output: 192.21.139.180

Example for generating an IPv4 address from Class A:

String ipClassA = mock.ipv4s().type(CLASS_A).val();
// Possible Output: 57.253.133.154

Example for generating an IPv4 address from Class A or Class B:

String classAorB = mock.ipv4s().types(CLASS_A, CLASS_B).val();
// Possible Output: 119.110.27.146

ipv6s()

This method is used to generate an arbitrary IPv6 address.

Example:

String ipv6 = mock.iPv6s().val();
// Possible Output: 35f1:b02f:8843:9abb:82bf:967a:34f5:ed8b

issns()

This method is used to generate arbitrary ISSN codes.

Example:

String issn  = mockNeat.issns().val();
// Possible Output: ISSN 6105-1470

localDates()

This method is used to generate arbitrary LocalDate objects.

Example of generating a random date in the past between: [1970, now()):

LocalDate localDate = mock.localDates().val();
// Possible Output: 1984-05-10

Example for generating a random date in the past between: [1987-1-30, now()):

LocalDate min = LocalDate.of(1987, 1, 30);
LocalDate past = mock.localDates().past(min).val();
// Possible Output: 2014-05-30

Example for generating a random date in the future between: [now(), 2020-1-1);

LocalDate max = LocalDate.of(2020, 1, 1);
LocalDate future = mock.localDates().future(max).val();
// At this moment this is the possible output: 2019-08-03

Example for generating a random date between [1989-1-1, 1993-1-1):

LocalDate start = LocalDate.of(1989, 1, 1);
LocalDate stop = LocalDate.of(1993, 1, 1);
LocalDate between = mock.localDates().between(start, stop).val();
// Possible Output: 1989-02-04

longs()

This method is used to generate int numbers.

Example for generating long numbers (negative or positive):

Long i1 = mock.longs().val();
// Possible Output : -2445487402940283422

Example for generating long numbers bounded by a certain value: [0, bound), where bound = 10:

Long bounded = mock.longs().bound(10).val();
// Possible Output: 8

Example for generating long numbers in a certain open range: [10, 20):

Long ranged = mock.longs().range(10, 20).val();
// Possible Output: 19

longSeq()

This method is used to generate sequence of numbers (longs).

Example for generating a sequence of longs starting with 0l, incrementing each time with 1l.

LongSeq seq = mock.longSeq();
for(int i = 0; i < 20; i++) {
    System.out.print(seq.val() + " ");
}
// Output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

Example for generating a sequence of longs starting with 5, incrementing with 2, and if it reaches a value bigger than 20 it resets back to 5:

LongSeq seq2 = mock.longSeq()
                   .start(5)
                   .increment(2)
                   .max(20)
                   .cycle(true);
for(int i = 0; i < 50; i++) {
    System.out.print(seq2.val() + " ");
}
// Output: 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 9 11 13 15 17 19 5 7 

Negative increments work, but instead of setting a max() value a min() needs to be set, otherwise it will default to Long.MIN_VALUE.

macs()

This method is used to generate arbitrary MAC addresses.

The MAC address can be formatted in a few ways. Each of these ways is mapped in the enum MACAddressFormatType: DASH_EVERY_2_DIGITS, COLON_EVERY_2_DIGITS, DOT_EVERY_2_DIGITS, DOT_EVERY_4_DIGITS.

Example for generating a MAC addresses and showing it in the format DOT_EVERY_4_DIGITS:

String mac = mock.macs().type(DOT_EVERY_4_DIGITS).val();
// Possible Output: 9a25.aa24.df7c

markovs()

This method is used to generate Markov Text.

For the moment this feature is not:

  • very memory efficient;
  • there aren't many options, but to generate text from Kafka's Metamorphosis.

Example for generating a 512 characters text:

String text = mock.markovs().size(512).type(KAFKA).val();
//Possible Output: In his efforts to muster all the things that concerned him. This meant not only in secret. For two whole days, all the harder. Across the room came in early in the doorway with a knife, he thought it was easy to see him. He had forgotten, but instead of being afraid, the charwoman stood in the direction of the bedrooms: come and give me a bit of him and seemed, at first, that was quite incapable of going backwards in a nice, gilded frame. It showed a lady fitted out with a few raisins and almonds; some chee

mimes()

This method is used to generate mime types (Eg.: application/msword, application/epub+zip, image/gif, text/html image/x-icon, etc).

String mime = m.mimes().val();
// Possible Output: application/vnd.visio

months()

This method is used to generate Months names. It is used to return Month objects.

Exmaple to generate a Month:

Month m = mock.months().val();
// Possible Output: FEBRUARY

Example to generate a month in the range [June, August] (summer):

Month summer = mock.months().rangeClosed(JUNE, AUGUST).val();
// Possible Output: August

Note: You can use the range() method for an open-interval.

Example to generate a month before the start of the summer, in range [January, June)

Month beforeSummer = mock.months().before(JUNE).val();
// Possible Output: APRIL

money()

This method is used to generate money amounts as Strings (Money Symbol + Sum of Money).

Example to generate a "fortune" in Japan. By fortune I mean a value in [100, 200) interval (YEN):

String japanFortune = mockNeat.money()
                                .locale(JAPAN)
                                .range(100, 200)
                                .val();
// Possible Output: ¥138

Example to generate millions of Euros:

String millions  = mockNeat.money()
                           .locale(GERMANY)
                           .range(1000000, 10000000)
                           .val();
Possible Output: 1.604.518,56

names()

This method is used to generate both first names and last names.

There is an enum class NameType that maps names into several categories:

  • NameType.FIRST_NAME : Contains both female and male first names;
  • NameType.FIRST_NAME_MALE : Contains only male first names;
  • NameType.FIRST_NAME_FEMALE : Contains only female first names;
  • NameType.FIRST_NAME_MALE_AMERICAN : Contains only male first names that are popular in the US;
  • NameType.FIRST_NAME_FEMALE_AMERICAN : Contains only female first names that are popular in the US;
  • NameType.LAST_NAME : Contains only last names;

To use those classifications the names() method must be used in conjunction with type().

Example to generate name of type FIRST_NAME_FEMALE :

String firstName = mock.names().type(FIRST_NAME_FEMALE).val();
// Possible Output: Allie

There are also shortcuts for generating first names, last names and full names with optional initials:

Example for generating an arbitrary first name (male or female):

String first = mock.names().first().val();

Example for generating an arbitrary last name:

String last = mock.names().last().val();

Example for generating a full name that has a 90% chance to contain an "initial":

String withInitial = mock.names().full(90).val();
// Possible Output: Bryce I. Hibma

naughtyStrings()

This is used to generate naughty Strings - strings that have a high probability of creating "problems" when they are used as user input.

There is a list of additional supported sub-methods:

  • naughtyStrings().cveVulnerabilities() ;
  • naughtyStrings().emoji() ;
  • naughtyStrings().fileInclusions() ;
  • naughtyStrings().inconousStrings() ;
  • naughtyStrings().japaneseEmoji() ;
  • naughtyStrings().msdosSpecialFileNames() ;
  • naughtyStrings().numeric() ;
  • naughtyStrings().quotations() ;
  • naughtyStrings().regionalIndicators() ;
  • naughtyStrings().reservedKeyWords() ;
  • naughtyStrings().rightToLeftStrings() ;
  • naughtyStrings().rubyInjection() ;
  • naughtyStrings().scriptInjection() ;
  • naughtyStrings().serverCodeInjection() ;
  • naughtyStrings().specialChars() ;
  • naughtyStrings().sqlInjection() ;
  • naughtyStrings().trickUnicode() ;
  • naughtyStrings().twoByteChars() ;
  • naughtyStrings().unicodeFont() ;
  • naughtyStrings().unicodeNumbers() ;
  • naughtyStrings().unicodeSubScriptSuperScript() ;
  • naughtyStrings().unicodeSymbols() ;
  • naughtyStrings().unicodeUpsideDown() ;
  • naughtyStrings().unwantedInterpolation() ;
  • naughtyStrings().xmlInjection() ;
  • naughtyStrings().zalgoText() ;

probabilities()

This method is used to generate objects based on associated probabilities.

Example for generating letters with the following probabilities: A - 10%, B - 20%, C - 50%, D - 20%:

String s = mockNeat.probabilites(String.class)
                    .add(0.1, "A")
                    .add(0.2, "B")
                    .add(0.5, "C")
                    .add(0.2, "D")
                    .val();

Note: The sum of the probabilities must exactly 1.0 when calling val.

Instead of constants, it's also possible to use any MockUnit as parameter.

Example for generating numbers in intervals based on probabilities:

  • Generating a number in interval [0, 100) - 20% chance;
  • Generating a number in interval [100, 200) - 50% chance;
  • Generating a number in interval [200, 300) - 30% chance;
Integer x = m.probabilites(Integer.class)
             .add(0.2, m.ints().range(0, 100))
             .add(0.5, m.ints().range(100, 200))
             .add(0.3, m.ints().range(200, 300))
             .val();

passwords()

This method is used to generate passwords.

Different types of password strengths can be generated, all strengths are mapped into the enum PassStrengthType: WEAK, MEDIUM, STRONG.

Example on how to generate a medium-strength password:

String medium = mock.passwords().type(MEDIUM).val();
// Possible Output: cent>ilLion

reflect()

This method is used to generate mock objects through reflection.

The full method signature is: <T> Reflect<T> reflect(Class<T> cls) where the input parameter cls represents the target class.

In order for this method to work the NO_ARG Constructor must exist and must be accessible.

The fields that are modified through reflection can be private, but cannot be final.

Example:

Test t = mock.reflect(Test.class)
             .field("x", mock.strings().size(10))
             .field("y", mock.ints().range(100, 200))
             .field("z", mock.bools())
             .val();
// Possible Output: Test{x='QeBhNPZNhK', y=2, z=false}

Instead of specifying a MockUnit (or constants) for every field the developer can call useDefaults(true). Doing this will activate a fallback mechanism that will populate each char, Character, short, Short, int, Integer, long, Long, float, Float, double, Double, String fields by default.

So for example if the Test class has 3 fields:

  • x -> String;
  • y -> Integer;
  • z -> Boolean.

We can use the default mechanism by doing this:

java

Test tR = mock.reflect(Test.class)
                        .useDefaults(true)
                        .val();

System.out.println("tR: " + tR);

// Possible Output: 
//         tR: Test{x='KksOzDmsy8kxCYxJs7aU5db4l255E4BC', y=57, z=false}

If you want to override the default mechanism you can use the type(Class<?>, MockUnit|Constant) method.

So let's take for example a class Test2 with 5 fields:

java
public class Test2 {
    private int x;
    private int y;
    private short z;
    private String w1;
    private String w2;

We can:

  • override the default fallback random generator for all String fields (random string of size 5);
  • override the default fallback random generator for all short fields (with a constant value of 5); by doing the following:
Test2 t4 = mock.reflect(Test2.class)
                        .useDefaults(true)
                        .type(String.class, mock.strings().size(5))
                        .type(Short.class, (short) 5)
                        .val();

System.out.println(t4);

//Possible Output:
// Test2{x=78, y=68, z=5, w1='1rlW5', w2='9aO3O'}

As you can see in the above example, all String fields have now a size of 5, while the short field z will always be the constant 5.

Note: The fields are modified directly and not through getter and setters.

regex()

The Regex class implements MockUnitString and it is used to generate random strings that match a given regex.

This feature is based on the Generex library.

Only a small subset of regular expressions work. Any non-trivial regex might fail.

Example for generating a "Lol" string:

String lolRegex = "LOo{3}L{10,15}!";
String lol = mock.regex(lolRegex).val();
// Possible Output: LOoooLLLLLLLLLLLLL!

Example for generating a number that has between 3 and 10 digits:

String numberRegex = "\\d{3,10}";
String number = mock.regex(numberRegex).val();
// Possible Output: 8296331806

Example for generating a code with a format: XX-nnnnn-xxxxx:

String codeRegex = "[A-Z]{2}-\\d{5}-[a-z]{5}";
String code = mock.regex(codeRegex).val();
// Possible Output: EI-54105-tjfdk

seq()

The Seq<T> is used to get values by iterating to an existing dictionary (DictType) or an Iterable<T>.

Iterating through the list. When we reach the "end" we start iterating again. Take care of concurrency issues:

List<String> list = Arrays.asList("a", "b", "c", "d");
mock.seq(list).cycle(true).list(100).consume(System.out::println);
// Prints ["a", "b", "c", "d", "a", "b"....]

Iterating through the list. When we reach the "end" a default value "X".

mock.seq(list).after("X").list(100).consume(System.out::println);
// Prints ["a", "b", "c", "d", "X", "X"...."X"]

sqlInserts()

This method is used to generate individual (or group of SQL Inserts).

For example:

MockNeat m = MockNeat.threadLocal();

SQLInsert oneInsert = m.sqlInserts()
                          .tableName("emp")
                          .column("id", m.intSeq().increment(10))
                          .column("first_name", m.names().first(), TEXT_BACKSLASH)
                          .column("last_name", m.names().last(), TEXT_BACKSLASH)
                          .column("username", m.users(), TEXT_BACKSLASH)
                          .column("email", m.emails(), TEXT_BACKSLASH)
                          .column("description", m.markovs().size(32).type(LOREM_IPSUM), TEXT_BACKSLASH)
                          .column("created", m.localDates().thisYear().display(BASIC_ISO_DATE), TEXT_BACKSLASH)
                          .val();

System.out.println(oneInsert);
// Possible Output:
// INSERT INTO emp (id, first_name, last_name, username, email, description, created) VALUES (0, 'Mohammad', 'Hibbets', 'lushtraci', 'villousslags@gmx.com', 'Ante ipsum primis in faucibus. E', '20180724');

The TEXT_BACKSLASH parameter is used to denote the fact the column is a text column, and the text is escaped.

For convenience, we can generate multiple SQL inserts, that can be stored in a SQLTable object.

MockNeat m = MockNeat.threadLocal();

int empTableRows = 100;
SQLTable empTable = m.sqlInserts()
                          .tableName("emp")
                          .column("id", m.intSeq().increment(10))
                          .column("first_name", m.names().first(), TEXT_BACKSLASH)
                          .column("last_name", m.names().last(), TEXT_BACKSLASH)
                          .column("username", m.users(), TEXT_BACKSLASH)
                          .column("email", m.emails(), TEXT_BACKSLASH)
                          .column("description", m.markovs().size(32).type(LOREM_IPSUM), TEXT_BACKSLASH)
                          .column("created", m.localDates().thisYear().display(BASIC_ISO_DATE), TEXT_BACKSLASH)
                          .table(empTableRows) // Generate a table instead of a single Insert
                          .val();

// After the table is generated we can modify the data in it

empTable.updateAll((i, insert) -> {
            // Update all the descriptions with 'N/A'
            insert.setValue("description", "N/A");
});

System.out.println(empTable);

// Select only the inserts from the table where the first_name starts with and print them

empTable
        .selectWhere((sqlInsert -> sqlInsert.getValue("first_name").startsWith("A")))
        .forEach(System.out::println);

shufflers()

The Shufflers class contain useful methods to create new shuffled strings, arrays or list from a source:

Method Description
T array(T[] source) Generic method to shuffle an array of Objects.
double[] arrayDouble(double[] source) Method to shuffle an array of double primitive values.
float[] arrayFloat(float[] source) Method to shuffle an array of float primitive values.
int[] arrayInt(int[] source) Method to shuffle an array of int primitive values.
long[] arrayLong(long[] source) Method to shuffle an array of long primitive values.
String string(String source) Method to shuffle a String.

Example for generating 5 random permutation of a given int[] array:

java
MockNeat mockNeat = MockNeat.threadLocal();
int[] x = { 1, 2, 3, 4, 5, 6 };

mockNeat.shufflers()
        .arrayInt(x)
        .stream().val()
        .limit(5)
        .forEach(arr -> System.out.println(Arrays.toString(arr)));

sscs()

This method is used to generate random Social Security Numbers.

Example:

String ssc = mock.sscs().val();
// Possible Output: 776-32-8981

strings()

This method is used to generate random String(s).

Additionally the size of the resulting String can be controlled using size().

Also the types of String objects we can use are mapped in the StringType enum:

  • NUMBERS;
  • ALPHA_NUMBERIC;
  • LETTERS;
  • HEX;
  • SPECIAL_CHARACTERS;

Example to generate a random string with a fixed-size of 15:

String str1 = mock.strings().size(15).val();
// Possible Output: 6GFLyfFRXjgC6wZ

Example to generate a random string with a variable-size between [1, 10]:

String str2 = mock.strings().size(mock.ints().range(1,10)).val();

As you can see in the example above it's possible to generate random strings with random size. The only consideration is that the constructed MockUnit passed as the parameter for size should not generate negative numbers, otherwise the call will fail.

Example to generate a String that only contains letters (no numbers or special characters) and it has a size of 5:

String onlyLetters = mock.strings().size(5).type(LETTERS).val();
// Possible Output: "P7S9ojfEyJ47ohy"

urls()

This method can be used to generate random URLs.

MockNeat m = MockNeat.threadLocal();

m.urls()
  .scheme(HTTP) // all the URLS have a HTTP scheme
//.auth() -- can include auth information in the URL
  .domain(POPULAR) // only popular domain names can be used 
  .host(ADVERB_VERB) 
  .ports(80, 8080, 8090) // only the following ports can be used
  .list(10) 
  .consume(System.out::println);

Possible output for the above example:

[http://www.tenthlyassays.net:8090, http://www.aflamecurr.io:8080, http://www.thirdlygirth.org:8080, http://www.foreprobates.net:8090, http://www.pokilyrile.org:80, http://www.cheerfullyapprizings.net:8090, http://www.whistlinglyunsettles.info:80, http://www.gratistrichinized.io:8080, http://www.sternwardssnuffle.gov:8090, http://www.yesterdaynix.edu:8090]

usStates()

This method is used to generate US States.

String usState = mockNeat.usStates().val();
String usStateISO2 = mockNeat.usStates().iso2().val();

words()

This method is used to generate random words.

It comes in 5 flavors:

  • words() : will return arbitrary words from the English vocabulary;
  • words().adverbs() : will return arbitrary adverbs from the English vocabulary;
  • words().adjectives() : will return arbitrary adjectives from the English vocabulary;
  • words().nouns() : will return arbitrary nouns from the English vocabulary;
  • words().verbs() : will return arbitrary verbs from the English vocabulary.

Example:

String word = mockNeat.words().val();

Example for generating a adjective/noun combination:

mockNeat.fmt("#{adj} #{noun}")
                .param("adj", mockNeat.words().adjectives().format(CAPITALIZED))
                .param("noun", mockNeat.words().nouns().format(LOWER_CASE))
                .list(10)
                .consume(list -> System.out.println(list));

// Possible Output: 
// [Pyelitic foehn, Slung dragonheads, Triste encumbrancer, Malicious culls, Tridactyl liege, Amicable wisteria, Stringed linns, Palladous idleness, Retractable cocksfoots, Unallayed bots]
Clone this wiki locally