Use MockConfig to customize the data generation process, such as setting value ranges or excluding specific fields.
Field Pattern Matching
Fields can be targeted using three wildcard patterns (case-insensitive):
*FieldWord*: Contains the word.*FieldWord: Ends with the word.FieldWord*: Starts with the word.
Configuration Scopes
- Global Configuration: Use
.globalConfig() to set defaults for all mocked objects (e.g., sizeRange, charSeed, or visibility of static/private/protected fields). - Field-level Configuration: Use
.subConfig("pattern") to apply specific ranges to fields matching a pattern. - Class-level Configuration: Use
.subConfig(Class.class, "pattern") to apply settings to specific fields within a specific class. - Exclusions: Use
.excludes("pattern") or .excludes(Class.class, "pattern") to prevent certain fields from being mocked.
Example Usage
MockConfig mockConfig = new MockConfig()
.globalConfig()
.setEnabledStatic(false)
.sizeRange(1, 1)
// Target fields by pattern
.subConfig("integerNum", "*float*", "double*")
.intRange(10, 11)
// Target specific class fields by pattern
.subConfig(BasicBean.class, "long*", "*date")
.dateRange("2018-11-20", "2018-11-30")
// Exclude fields
.excludes("*List*", "*Set*");
BasicBean bean = JMockData.mock(BasicBean.class, mockConfig);
MockConfig mockConfig = new MockConfig()
// 全局配置
.globalConfig()
.setEnabledStatic(false);
.setEnabledPrivate(false);
.setEnabledPublic(false);
.setEnabledProtected(false);
.sizeRange(1,1)
.charSeed((char) 97, (char) 98)
.byteRange((byte) 0, Byte.MAX_VALUE)
.shortRange((short) 0, Short.MAX_VALUE)
// 某些字段(名等于integerNum的字段、包含float的字段、double开头的字段)配置
.subConfig("integerNum","*float*","double*")
.intRange(10, 11)
.floatRange(1.22f, 1.50f)
.doubleRange(1.50,1.99)
// 某个类的某些字段(long开头的字段、date结尾的字段、包含string的字段)配置。
.subConfig(BasicBean.class,"long*","*date","*string*")
.longRange(12, 13)
.dateRange("2018-11-20", "2018-11-30")
.stringSeed("SAVED", "REJECT", "APPROVED")
.sizeRange(1,1)
// 全局配置
.globalConfig()
// 排除所有包含list/set/map字符的字段。表达式不区分大小写。
.excludes("*List*","*Set*","*Map*")
// 排除所有Array开头/Boxing结尾的字段。表达式不区分大小写。
.excludes(BasicBean.class,"*Array","Boxing*");
BasicBean basicBean = JMockData.mock(BasicBean.class, mockConfig);