Xander

V2

2022/11/06阅读:65主题:橙心

Instancio Random Test Data Generator for Java

What is Instancio

Source:Instancio Random Test Data Generator for Java

Instancio is a Java library that automatically creates and populates objects for your unit tests.

The article describes two common uses of this open source project:

  1. Automating Data Setup
  2. Generating a Stream of Objects

Address

Below is the URL of the project:

instancio/instancio: A library for creating fully populated objects for your unit tests. (github.com)

Docs

User Guide - Instancio

Why need Instancio?

Some projects will have classes with static helper methods for creating test objects, but that’s still extra code that needs to be maintained. A better alternative is to delegate this task to a library.

Start

Following the project's instructions, you may see an error in IDEA:

![[maven imports.png]]

I personally recommend using an earlier version here, and I suspect the author may not have released the latest version to the Maven repository.

![[maven import fix.png]]

Automating Data Setup

Instancio is a library that can help automate data setup by generating test data with a single method call (or a few method calls if you need to customise the data)


  
    @Test  
    public void verifyCustomer() {  
        // Creates a fully-populated instance of Customer  
        TestReportDTO testReportDTO = Instancio.create(TestReportDTO.class);  
        System.err.println(testReportDTO);  
        // ... etc  
    }/**  
  
     Results:  
     TestReportDTO{test0='UVRQEOY', test1='NCQNBZW', test2='CEGLJNB', test4='AMUXHGQA', test5='AFUMZ', test6='SHTUGOVM'}  
 */

Instancio.create(TestReportDTO.class) will generate a fully-populated TestReportDTO instance,Instancio will generate non-null values and non-empty collections and arrays.

The variable provides access to built-in generators for customising generated values. Some of the things you can do:gen

   @Test  
    public void verifyCustomer() {  
        // Creates a fully-populated instance of Customer  
        TestReportDTO testReportDTO = Instancio.create(TestReportDTO.class);  
        TestReportDTO testReportDTO1 = Instancio.of(TestReportDTO.class)  
                // 对于指定字段构建随机值  
                .generate(field("testInt7"), gen -> gen.ints().range(18, 65))  
//                .generate(field(TestReportDTO.class, "number"), gen -> gen.text().pattern("#d#d#d-#d#d-#d#d"))  
                .create()
;  
        System.err.println(testReportDTO);  
        System.err.println(testReportDTO1);  
        // ... etc  
    }/**  
  
     Results:  
     result1:  
     TestReportDTO{test0='PJY', test1='MTEGQ', test2='KYXR', test4='ZNLCOYHTKB', test5='ZXT', test6='JXAX', testInt7=7320, wordName='DYLIFZNQPO'}     result2:     TestReportDTO{test0='ORLVPNGILH', test1='VIAIC', test2='QRHKNNVYE', test4='HCEGVALHE', test5='QDKLMQR', test6='XXNQYS', testInt7=63, wordName='MYHFGNC'}     */

More usage:

// string of at least 10 chars, allow empty strings
gen.string().allowEmpty().minLength(10
// string with two upper case and two digits, e.g. "AB-12"
gen.text().pattern("#C#C-#d#d"
// past LocalDate
gen.temporal().localDate().past() 
// array of length 5
gen.arrays().length(5
// integer within given range
gen.ints().range(110

In addition to the method, the API provides a and methods. The first method accepts the value to set, while the second a of the value. For example:generate()set()supply()java.util.function.Supplier

        TestReportDTO testReportDTO1 = Instancio.of(TestReportDTO.class)  
                // 对于指定字段构建随机值  
                .generate(field("testInt7"), gen -> gen.ints().range(18, 65))  
                .supply(all(LocalDateTime.class), () -> LocalDateTime.now())  
//                .generate(field(TestReportDTO.class, "number"), gen -> gen.text().pattern("#d#d#d-#d#d-#d#d"))  
                .create()
;

The results of the run are as follows

TestReportDTO{test0='WWJUTAC', test1='NLOFBGWP', test2='TYIDBERNQ', test4='RDLO', test5='PFUJAQGO', test6='QHDOAY', testInt7=26, wordName='TDDSYT', localDateTime=2022-11-06T09:41:47.288423500}

Generating a Stream of Objects

The method creates an infinite stream, the following will create a map of 5 customers with as the map key:java.util.stream.Stream``Instancio.stream()``limit()``id

// 生成 map
 Map<String, TestReportDTO> customerMap = Instancio.stream(TestReportDTO.class)  
        .limit(5)  
        .collect(Collectors.toMap(TestReportDTO::getTest0Function.identity()))
;  
System.err.println(customerMap);

The results of the run are as follows

{FDVK=TestReportDTO{test0='FDVK', test1='ZJKJZKNL', test2='WFWXEAWF', test4='PRTV', test5='VLSWLZK', test6='AQBP', testInt7=9227, wordName='BPKAZVLBIA', localDateTime=2060-01-18T03:54:06.570350101}, KXUMD=TestReportDTO{test0='KXUMD', test1='TZPDY', test2='JILT', test4='CYNGJEAR', test5='KTWWPYK', test6='BASRMK', testInt7=5686, wordName='GOKSDIUKY', localDateTime=2042-05-10T06:01:19.040367523}, LJKTHT=TestReportDTO{test0='LJKTHT', test1='MKNN', test2='ARCWBK', test4='ZFXB', test5='KEXELG', test6='DPZSPXGA', testInt7=7137, wordName='SKSXLIUONE', localDateTime=2033-10-31T15:45:25.799976707}, RQQZHZRXTN=TestReportDTO{test0='RQQZHZRXTN', test1='ORSHFRJU', test2='ICGIEC', test4='TMEXFTZD', test5='LYNWHEJCNM', test6='EHHM', testInt7=177, wordName='JLP', localDateTime=2052-09-20T09:10:18.119338575}, GGHZDFP=TestReportDTO{test0='GGHZDFP', test1='BGLU', test2='SBIPR', test4='EGYLTP', test5='OUQFZZEKZ', test6='QLZBEAZKW', testInt7=7836, wordName='QAJUQVYNR', localDateTime=1996-04-09T13:24:36.296079785}}

The content of the production List object can also be carried out by referring to the above way to generate a single object:

Map<UUID, Customer> customerMap = Instancio.of(Customer.class)
.generate(all(LocalDateTime.class), gen -> gen.temporal().localDateTime().past())
.set(field(Phone.class, "countryCode"), "+1")
  .stream()
.limit(5)
.collect(Collectors.toMap(Customer::getIdFunction.identity()))
;

Others

For more gameplay suggestions, take a look at the documentation

User Guide - Instancio

You can try more:

  • Creating instances of generic classes
  • Creating models that act as a cookie cutter template for generating objects

分类:

阅读

标签:

阅读

作者介绍

Xander
V2

摸鱼JAVA工程师 公众号:懒时小窝