您可以使用一個名爲MockNeat的庫以編程方式用可以作爲「真實」傳遞的任意數據「填充」對象。
例如,在奧得來填充一個對象,你可以去看看的reflect()方法:
// Creates a MockNeat object that internally uses
// a ThreadLocalRandom.
MockNeat m = MockNeat.threadLocal();
List<Employee> companyEmployees =
m.reflect(Employee.class) // The class we are mocking
.field("uniqueId",
m.uuids()) // Generates a random unique identifier
.field("id",
m.longSeq()) // Generates long numbers in a sequence
.field("fullName",
m.names().full()) // Generates a full name for the employer
.field("companyEmail",
m.emails().domain("company.com")) // Generates a company email with a given domain
.field("personalEmail",
m.emails()) // Generates an arbitrary email without domain constraints
.field("salaryCreditCard",
m.creditCards().types(AMERICAN_EXPRESS, MASTERCARD)) // Generate credit card numbers of 'types'
.field("external",
m.bools().probability(20.0)) // Generates Boolean values with 20% probability of obtaining True
.field("hireDate",
m.localDates().past(of(1999, 1, 1))) // Generatest a date in the past, but greater than 01.01.1987
.field("birthDate",
m.localDates().between(of(1950, 1, 1), of(1994, 1, 1))) // Generates a data in the given range
.field("pcs",
m.reflect(EmployeePC.class) // Mock an EmployeePC object
.field("uuid",
m.uuids()) // Generates an unique identifier
.field("username",
m.users()) // Generates an arbitrary username
.field("operatingSystem",
m.from(new String[]{"Linux", "Windows 10", "Windows 8"})) // Randomly selects an OS from the given List
.field("ipAddress",
m.ipv4s().type(CLASS_B)) // Generates a CLASS B IPv4 Address
.field("macAddress",
m.macs()) // Generates a MAC Address
.list(2)) // Creates a List<EmployeePC> with 2 values
.list(1000) // Creates a List<Employee> with 1000 values
.val(); // Returns the list
聽起來很有趣!去吧! –
有趣的方法。就像你想的那樣! :) – SudoRahul
你有任何字段和/或數據類型的特定約束,你的隨機值必須服從是有效的嗎? (例如,數值範圍,字符串的最小/最大長度,字符串中允許的字符,...) – isnot2bad