随机数据生成器

时间:2013-10-03 09:24:05

标签: java

我必须用随机值填充给定对象的每个属性。 这些是我对它的要求:

  • 所有属性均为原生Java类型(intdoubleString等)
  • 我可以使用反射
  • 我可以使用Spring DirectFieldAccessor

我不想重新发明方形轮,所以我更愿意问。 现在我想出了这个:

获取所有属性名称:

Field field : myObject.getClass().getDeclaredFields()

迭代这些领域并获得他们的课程。

对每个已知的本机Java类型使用巨型switch语句并生成随机值。

您怎么看?

4 个答案:

答案 0 :(得分:2)

另一个选项是QuickTheories。看起来像:

import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.SourceDSL.*;

public class SomeTests {

  @Test
  public void addingTwoPositiveIntegersAlwaysGivesAPositiveInteger(){
    qt()
      .forAll(integers().allPositive()
          , integers().allPositive())
      .check((i,j) -> i + j > 0); 
  }

  @Test
  public void someTheoryOrOther(){
    qt()
      .forAll(integers().allPositive()
          , strings().basicLatinAlphabet().ofLengthBetween(0, 10)
          , lists().allListsOf(integers().all()).ofSize(42))
      .assuming((i,s,l) -> s.contains(i.toString())) // <-- an assumption
      .check((i,s,l) -> l.contains(i) && s.contains(i.toString()));
  }
}

答案 1 :(得分:1)

因为这是一个用于随机数据生成的randomizer。如您所述,这只使用了Reflection的概念。 它检查字段上提到的注释,并根据它检查Provider类。通过 Person 模型类。 它有一些原始的和非原始的领域。

public class Person {

   @FirstName
   public String mFirstName;

   @LastName
   public String mLastName;

   @Number(min = 14,max = 25,decimals = 0)
   public int age;

   @Email
   public String mEmailId;

   @ReferenceRecord(clazz = Address.class)
   public Address address;

}

@ReferencedRecord
public class Address {

   @StreetAddress
   public String streetAddress;

   @State
   public String state;
}

//Generate random 100 Person(Model Class) object 
Generator<Person> generator = new Generator<>(Person.class);  
List<Person> persons = generator.generate(100);                          

由于可以使用注释访问许多内置数据生成器,您还可以使用 @CustomGenerator 注释构建自定义数据生成器。我建议您浏览库页面上提供的文档。

答案 2 :(得分:0)

您可以使用名为MockNeat的库以编程方式“填充”您的对象,其中任意数据可以作为“真实”传递。

例如,在填充对象的oder中,您可以查看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

答案 3 :(得分:0)

您可以尝试Random-JPA,该框架旨在生成随机数据。设置很小。

用法:

    var filePath: URL! {
        didSet {
            // Reset the current fields
            self.filenameLabel.text = "Loading"
            self.createdDateLabel.text = "Loading"
            self.fileSizeLabel.text = "Loading"

            // And then fetch the contents
            fetchContents()
        }
    }
相关问题