├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .travis.yml ├── LICENSE ├── PROCESS.md ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main └── groovy │ └── nl │ └── topicus │ └── overheid │ └── javafactorybot │ ├── BaseFactory.groovy │ ├── Evaluator.groovy │ ├── Factory.groovy │ ├── FactoryContext.groovy │ ├── FactoryManager.groovy │ ├── definition │ ├── AbstractFactoryAttribute.groovy │ ├── Association.groovy │ ├── Attribute.groovy │ ├── Definition.groovy │ ├── ManyAssociation.groovy │ ├── Trait.groovy │ └── ValueAttribute.groovy │ ├── exception │ ├── EvaluationException.groovy │ └── TraitNotFoundException.groovy │ └── factory │ ├── FactoryAttributes.groovy │ ├── FactoryDSL.groovy │ ├── FactoryHooks.groovy │ └── FactoryTraits.groovy └── test ├── groovy └── nl │ └── topicus │ └── overheid │ └── javafactorybot │ ├── BaseFactoryTest.groovy │ └── test │ └── factory │ ├── ArticleFactory.groovy │ ├── CommentFactory.groovy │ └── UserFactory.groovy └── java └── nl └── topicus └── overheid └── javafactorybot └── test └── model ├── Article.java ├── Comment.java └── User.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | 4 | target 5 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.net.*; 21 | import java.io.*; 22 | import java.nio.channels.*; 23 | import java.util.Properties; 24 | 25 | public class MavenWrapperDownloader { 26 | 27 | /** 28 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 29 | */ 30 | private static final String DEFAULT_DOWNLOAD_URL = 31 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"; 32 | 33 | /** 34 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 35 | * use instead of the default one. 36 | */ 37 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 38 | ".mvn/wrapper/maven-wrapper.properties"; 39 | 40 | /** 41 | * Path where the maven-wrapper.jar will be saved to. 42 | */ 43 | private static final String MAVEN_WRAPPER_JAR_PATH = 44 | ".mvn/wrapper/maven-wrapper.jar"; 45 | 46 | /** 47 | * Name of the property which should be used to override the default download url for the wrapper. 48 | */ 49 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 50 | 51 | public static void main(String args[]) { 52 | System.out.println("- Downloader started"); 53 | File baseDirectory = new File(args[0]); 54 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 55 | 56 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 57 | // wrapperUrl parameter. 58 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 59 | String url = DEFAULT_DOWNLOAD_URL; 60 | if(mavenWrapperPropertyFile.exists()) { 61 | FileInputStream mavenWrapperPropertyFileInputStream = null; 62 | try { 63 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 64 | Properties mavenWrapperProperties = new Properties(); 65 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 66 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 67 | } catch (IOException e) { 68 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 69 | } finally { 70 | try { 71 | if(mavenWrapperPropertyFileInputStream != null) { 72 | mavenWrapperPropertyFileInputStream.close(); 73 | } 74 | } catch (IOException e) { 75 | // Ignore ... 76 | } 77 | } 78 | } 79 | System.out.println("- Downloading from: : " + url); 80 | 81 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 82 | if(!outputFile.getParentFile().exists()) { 83 | if(!outputFile.getParentFile().mkdirs()) { 84 | System.out.println( 85 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 86 | } 87 | } 88 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 89 | try { 90 | downloadFileFromURL(url, outputFile); 91 | System.out.println("Done"); 92 | System.exit(0); 93 | } catch (Throwable e) { 94 | System.out.println("- Error downloading"); 95 | e.printStackTrace(); 96 | System.exit(1); 97 | } 98 | } 99 | 100 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 101 | URL website = new URL(urlString); 102 | ReadableByteChannel rbc; 103 | rbc = Channels.newChannel(website.openStream()); 104 | FileOutputStream fos = new FileOutputStream(destination); 105 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 106 | fos.close(); 107 | rbc.close(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topicusoverheid/java-factory-bot/bfb3d571a90211508ea09d2dad6a404d352acc5e/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PROCESS.md: -------------------------------------------------------------------------------- 1 | # Building process 2 | 3 | ``` 4 | /-----------\ evaluate(override?) 5 | build(overrides) ---> | init | --------------------> [Attribute] 6 | \-----------/ <-------------------------/ 7 | | 8 | | - onAfterInit(attributes) 9 | | - traits.each(it.onAfterInit(attributes)) 10 | | 11 | | attributes (Map) 12 | V 13 | /-----------\ 14 | | construct | 15 | \-----------/ 16 | | 17 | | object (T) 18 | V 19 | /-----------\ 20 | | finalize | 21 | \-----------/ 22 | | 23 | | - onAfterBuild(object) 24 | | - traits.each(it.onAfterBuild(object)) 25 | | 26 | build(object) ---------\ | object (T) 27 | V V 28 | object /-----------\ 29 | <------------------- | persist | 30 | \-----------/ 31 | | 32 | | object (T) 33 | V 34 | /-----------\ evaluate(object, override?) 35 | | combine | --------------------> [Attribute] 36 | \-----------/ <-------------------------/ 37 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java-factory-bot 2 | 3 | [![Build Status](https://travis-ci.org/topicusoverheid/java-factory-bot.svg?branch=master)](https://travis-ci.org/topicusoverheid/java-factory-bot) 4 | 5 | A library for creating objects as test data, with support for persisting the objects in a database. 6 | 7 | Using factories, creating default sane test objects is simple, while individual attibutes can easily be tweaked. 8 | Combining these with [java-faker](https://github.com/DiUS/java-faker) allows to boost your tests, or seed your database 9 | for demo and testing purposes. 10 | 11 | This library is inspired by [factory_bot](https://github.com/thoughtbot/factory_bot), a popular gem for ruby. 12 | 13 | ## Example 14 | 15 | Given a model for an `Article` and a `User` (getters and setters are omitted): 16 | 17 | ```java 18 | @Data 19 | public class Article { 20 | private String title; 21 | private String content; 22 | private Date creationDate; 23 | private User author; 24 | } 25 | 26 | @Data 27 | public class User { 28 | private String username; 29 | private String firstName; 30 | private String lastName; 31 | private String email; 32 | } 33 | ``` 34 | 35 | we can define factories like 36 | 37 | ```groovy 38 | class ArticleFactory extends Factory
{ 39 | Map attributes = [ 40 | title : value { faker.lorem().sentence() }, 41 | content : value { faker.lorem().paragraph() }, 42 | creationDate: value { faker.date().past(20, TimeUnit.DAYS) }, 43 | author : hasOne(UserFactory) 44 | ] 45 | } 46 | 47 | class UserFactory extends Factory { 48 | Map attributes = [ 49 | username : value { faker.name().username() }, 50 | firstName: value { faker.name().firstName() }, 51 | lastName : value { faker.name().lastName() }, 52 | email : value { "${get("firstName")}.${get("lastName")}@example.com" } 53 | ] 54 | } 55 | ``` 56 | 57 | and create objects using 58 | 59 | ```java 60 | Article article = new ArticleFactory().build() 61 | ``` 62 | 63 | which generates an article with default random but sane attributes. Individual attributes or relations can be overriden 64 | by passing them in a map: 65 | 66 | ```groovy 67 | Article article = new ArticleFactory().build([title: "Foo", user: [username: "johndoe"]]) 68 | ``` 69 | 70 | For documentation and more examples, visit the [wiki](https://github.com/topicusoverheid/java-factory-bot/wiki). 71 | 72 | ## Installation 73 | 74 | ### Maven 75 | 76 | Add the following to your dependencies: 77 | 78 | 79 | nl.topicus.overheid 80 | java-factory-bot 81 | 0.2.0 82 | test 83 | 84 | 85 | ### Gradle 86 | 87 | Add the following line to the dependency section of `build.gradle` 88 | 89 | compile "nl.topicus.overheid:java-factory-bot:0.2.0" 90 | 91 | ## Building 92 | 93 | Execute `./mvnw install` to build and test the library. 94 | 95 | ### Source and javadoc 96 | 97 | To generate jars containing the source and javadoc, enable the `source` profile. Example: 98 | 99 | ./mvnw install -P source 100 | 101 | ### Deploy 102 | 103 | To deploy the library to maven central, enable the `release` and `source` profiles and perform the `deploy` goal: 104 | 105 | ./mvnw clean install deploy -P source -P release 106 | 107 | ## Licence 108 | 109 | This library is released under the Apache 2.0 licence, which you can find [here](LICENSE). -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 5 | 4.0.0 6 | 7 | nl.topicus.overheid 8 | java-factory-bot 9 | 0.2.0 10 | jar 11 | 12 | java-factory-bot 13 | Library for creating objects as test data 14 | https://github.com/topicusoverheid/java-factory-bot 15 | 16 | 17 | 18 | Apache 2.0 License 19 | http://www.apache.org/licenses/LICENSE-2.0 20 | repo 21 | A business-friendly OSS license 22 | 23 | 24 | 25 | 26 | 27 | dennis.schroer 28 | Dennis Schroer 29 | dennis.schroer@topicus.nl 30 | Topicus 31 | https://topicus.nl 32 | 33 | Project-Administrator 34 | Developer 35 | 36 | 37 | 38 | 39 | 40 | scm:git:https://github.com/topicusoverheid/java-factory-bot.git 41 | scm:git:https://github.com/topicusoverheid/java-factory-bot.git 42 | https://github.com/topicusoverheid/java-factory-bot 43 | 44 | 45 | 46 | 47 | 1.8 48 | 1.8 49 | UTF-8 50 | UTF-8 51 | 3BFDF857 52 | 53 | 54 | 1.5 55 | 2.4.0 56 | 2.4.3-01 57 | 2.9.2-01 58 | 0.14 59 | 1.16.10 60 | 1.1-groovy-2.4 61 | 62 | 63 | 3.7.0 64 | 3.0.1 65 | 2.1 66 | 1.6.7 67 | 1.5 68 | 69 | 70 | 71 | 72 | ossrh 73 | https://oss.sonatype.org/content/repositories/snapshots 74 | 75 | 76 | ossrh 77 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 78 | 79 | 80 | 81 | 82 | 83 | 84 | org.codehaus.groovy 85 | groovy-all 86 | ${groovy.version} 87 | 88 | 89 | com.github.javafaker 90 | javafaker 91 | ${javafaker.version} 92 | 93 | 94 | org.projectlombok 95 | lombok 96 | ${lombok.version} 97 | provided 98 | 99 | 100 | org.spockframework 101 | spock-core 102 | ${spock.version} 103 | test 104 | 105 | 106 | 107 | 108 | 109 | 110 | org.codehaus.groovy 111 | groovy-all 112 | 113 | 114 | com.github.javafaker 115 | javafaker 116 | 117 | 118 | org.projectlombok 119 | lombok 120 | provided 121 | 122 | 123 | org.spockframework 124 | spock-core 125 | test 126 | 127 | 128 | 129 | 130 | 131 | 132 | maven-compiler-plugin 133 | ${maven-compiler-plugin.version} 134 | 135 | groovy-eclipse-compiler 136 | 137 | lombok.launch.Agent 138 | 139 | 140 | 141 | 142 | org.codehaus.groovy 143 | groovy-eclipse-compiler 144 | ${groovy-eclipse-compiler.version} 145 | 146 | 147 | org.codehaus.groovy 148 | groovy-eclipse-batch 149 | ${groovy-eclipse-batch.version} 150 | 151 | 152 | 153 | 154 | 156 | 157 | org.codehaus.groovy 158 | groovy-eclipse-compiler 159 | ${groovy-eclipse-compiler.version} 160 | true 161 | 162 | 163 | 164 | 165 | 166 | 167 | source 168 | 169 | 170 | 171 | 172 | org.apache.maven.plugins 173 | maven-source-plugin 174 | ${maven-source-plugin.version} 175 | 176 | 177 | attach-sources 178 | verify 179 | 180 | jar-no-fork 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | com.bluetrainsoftware.maven 189 | groovydoc-maven-plugin 190 | ${groovydoc-maven-plugin.version} 191 | 192 | 193 | attach-docs 194 | package 195 | 196 | attach-docs 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | release 206 | 207 | 208 | 209 | 210 | org.sonatype.plugins 211 | nexus-staging-maven-plugin 212 | ${nexus-staging-maven-plugin.version} 213 | true 214 | 215 | ossrh 216 | https://oss.sonatype.org/ 217 | true 218 | 219 | 220 | 221 | 222 | 223 | org.apache.maven.plugins 224 | maven-gpg-plugin 225 | ${maven-gpg-plugin.version} 226 | 227 | 228 | sign-artifacts 229 | verify 230 | 231 | sign 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/BaseFactory.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | import com.github.javafaker.Faker 4 | import nl.topicus.overheid.javafactorybot.definition.Definition 5 | import nl.topicus.overheid.javafactorybot.exception.TraitNotFoundException 6 | 7 | import java.lang.reflect.ParameterizedType 8 | 9 | /** 10 | * A factory is a special class which is able to generate new valid objects, for testing purposes. 11 | * These objects can be randomized by using a faker. 12 | * 13 | * @param < M > The type of the generated object 14 | * @param < F > The type of the faker of this factory. This allows to override the faker with a custom implementation. 15 | */ 16 | abstract class BaseFactory extends Definition { 17 | /** 18 | * A Faker instance which can be used to generate random attribute values. 19 | * 20 | * @link https://github.com/DiUS/java-faker 21 | */ 22 | abstract F getFaker() 23 | 24 | /** 25 | * Returns the type of the object which is created by this factory. By default, this method returns the type 26 | * specified as generic type of this factory. 27 | * 28 | * @return The type of the object which is created by this factory. 29 | */ 30 | Class getObjectType() { 31 | // Reflection magic to determine the type of the generated object 32 | // Based on https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection 33 | try { 34 | ((ParameterizedType) this.class.genericSuperclass).actualTypeArguments[0] as Class 35 | } catch (ClassCastException e) { 36 | // This exception explains better what you did wrong 37 | throw new IllegalStateException("Object type of ${this.class.simpleName} could not be determined. Did you forget to add a type parameter to the factory?", e) 38 | } 39 | } 40 | 41 | /** 42 | * Returns the passed object. 43 | *

44 | * This method exists so it is possible to completely override a relation by passing your own instance, or null. 45 | * 46 | * @param object The custom instance of the object. 47 | * @return The passed object 48 | */ 49 | M build(M object) { 50 | // This check is required. When creating an empty map in groovy, it does not conform to the type Map. Due to this, the 51 | // map is passed to this method. To handle this situation, the correct method is used when a map is given. 52 | if (object instanceof Map) { 53 | build(object as Map, []) 54 | } else { 55 | persist(object, FactoryManager.instance.currentContext) 56 | } 57 | } 58 | 59 | /** 60 | * Returns a new instance that is not saved. 61 | *

62 | * In normal usage, this method should not be overriden. If you want to change how the object is built, use 63 | * {@link #onAfterBuild} or {@link #construct}. 64 | * 65 | * @return The new instance. 66 | */ 67 | M build() { 68 | build([:]) 69 | } 70 | 71 | /** 72 | * Returns a new instance that is not saved. 73 | *

74 | * In normal usage, this method should not be overriden. If you want to change how the object is built, use 75 | * {@link #onAfterBuild} or {@link #construct}. 76 | * 77 | * @param overrides Additional overrides to use when building a new object. 78 | * Build parameters allow to define custom values for attributes and relations. 79 | * @param traits A list of traits to apply to new object. A trait is basically a collection of attribute/relation 80 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 81 | * @return The new instance. 82 | */ 83 | M build(Map overrides, List traits = null) { 84 | def evaluator = new Evaluator(this, traits, overrides) 85 | combine( 86 | persist( 87 | finalize( 88 | construct( 89 | initialize(evaluator) 90 | ), 91 | evaluator 92 | ), 93 | FactoryManager.instance.currentContext 94 | ), 95 | evaluator 96 | ) 97 | } 98 | 99 | /** 100 | * Returns a new instance that is not saved. 101 | *

102 | * In normal usage, this method should not be overriden. If you want to change how the object is built, use 103 | * {@link #onAfterBuild} or {@link #construct}. 104 | * 105 | * @param traits A list of traits to apply to new object. A trait is basically a collection of attribute/relation 106 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 107 | * @return The new instance. 108 | */ 109 | M build(List traits) { 110 | build([:], traits) 111 | } 112 | 113 | /** 114 | * Returns a new instance that is not saved. 115 | *

116 | * In normal usage, this method should not be overriden. If you want to change how the object is built, use 117 | * {@link #onAfterBuild} or {@link #construct}. 118 | * 119 | * @param traits An array of traits to apply to new object. A trait is basically a collection of attribute/relation 120 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 121 | * @return The new instance. 122 | */ 123 | M build(String... traits) { 124 | build([:], traits.toList()) 125 | } 126 | 127 | /** 128 | * Returns the passed object, after it is saved. 129 | *

130 | * This method exists so it is possible to completely override a relation by passing your own instance, or null. 131 | *

132 | * To persist the object, the current context (@link FactoryManager#currentContext} is temporarily set to {@link FactoryManager#createContext}. 133 | * This context specifies the strategy to use to persist the object. 134 | * 135 | * @param object The custom instance of the object. 136 | * @return The passed object, after is saved. 137 | */ 138 | M create(M object) { 139 | doInCreateContext { build(object) } 140 | } 141 | 142 | /** 143 | * Returns a new instance that is saved. 144 | *

145 | * To persist the object, the current context (@link FactoryManager#currentContext} is temporarily set to {@link FactoryManager#createContext}. 146 | * This context specifies the strategy to use to persist the object. 147 | * 148 | * @return The new saved instance. 149 | */ 150 | M create() { 151 | doInCreateContext { build() } 152 | } 153 | 154 | /** 155 | * Returns a new instance that is saved. 156 | *

157 | * To persist the object, the current context (@link FactoryManager#currentContext} is temporarily set to {@link FactoryManager#createContext}. 158 | * This context specifies the strategy to use to persist the object.. 159 | * 160 | * @param overrides Additional overrides to use when building a new object. 161 | * Build parameters allow to define custom values for attributes and relations. 162 | * @param traits A list of traits to apply to new object. A trait is basically a collection of attribute/relation 163 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 164 | * @return The new saved instance. 165 | */ 166 | M create(Map overrides, List traits = null) { 167 | doInCreateContext { build(overrides, traits) } 168 | } 169 | 170 | /** 171 | * Returns a new instance that is saved. 172 | *

173 | * To persist the object, the current context (@link FactoryManager#currentContext} is temporarily set to {@link FactoryManager#createContext}. 174 | * This context specifies the strategy to use to persist the object.. 175 | * 176 | * @param traits A list of traits to apply to new object. A trait is basically a collection of attribute/relation 177 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 178 | * @return The new saved instance. 179 | */ 180 | M create(List traits) { 181 | doInCreateContext { build(traits) } 182 | } 183 | 184 | /** 185 | * Returns a new instance that is saved. 186 | *

187 | * To persist the object, the current context (@link FactoryManager#currentContext} is temporarily set to {@link FactoryManager#createContext}. 188 | * This context specifies the strategy to use to persist the object.. 189 | * 190 | * @param traits An array of traits to apply to new object. A trait is basically a collection of attribute/relation 191 | * updates, meant to create an object representing a certain state. The possible traits are specified in the factory. 192 | * @return The new saved instance. 193 | */ 194 | M create(String... traits) { 195 | doInCreateContext { build(traits) } 196 | } 197 | 198 | /** 199 | * Returns a list of new instances that are not saved. 200 | * 201 | * @param amount The amount of instances to build. 202 | * @param overrides Additional overrides to use when building a new object. 203 | * @return As list of new instances. 204 | */ 205 | List buildList(int amount, Map overrides = null) { 206 | List result = new ArrayList<>(amount) 207 | amount.times { result.add(overrides == null ? build() : build(overrides)) } 208 | result 209 | } 210 | 211 | /** 212 | * Returns a list of new instances that are not saved. 213 | * 214 | * @param overrides A list of additional overrides. 215 | * Each element in the list is applied to {@link #build}. 216 | * So the size of the result is the same as the amount of elements in this list. 217 | * @return As list of new instances. 218 | */ 219 | List buildList(List overrides) { 220 | overrides.collect({ (M) this.build(it) }) 221 | } 222 | 223 | /** 224 | * Returns a list of new instances that are saved. 225 | * 226 | * @param amount The amount of instances to build. 227 | * @param overrides Additional overrides to use when building a new object. 228 | * @return As list of new saved instances. 229 | */ 230 | List createList(int amount, Map overrides) { 231 | doInCreateContext { buildList(amount, overrides) } 232 | } 233 | 234 | /** 235 | * Returns a list of new instances that are saved. 236 | * 237 | * @param overrides A list of additional overrides. 238 | * Each element in the list is applied to {@link #build}. 239 | * So the size of the result is the same as the amount of elements in this list. 240 | * @return As list of new saved instances. 241 | */ 242 | List createList(List overrides) { 243 | doInCreateContext { buildList(overrides) } 244 | } 245 | 246 | // Build process steps down here 247 | 248 | /** 249 | * First step of the build process. Takes the evaluator containing the factory and user specified overrides, and 250 | * outputs a map of attribute names to values which should be used to construct the object. 251 | * 252 | * In this step, all onAfterAttribute hooks are called. 253 | * 254 | * @param evaluator The evaluator to use in this step. 255 | * @return A map containing values of attributes to be used for constructing the boject. 256 | */ 257 | protected Map initialize(Evaluator evaluator) { 258 | applyAfterAttributesHooks(evaluator.evaluateForInitialize(), evaluator.traits) 259 | } 260 | 261 | /** 262 | * Second step of build process. Actual builder of the object, which creates the instance using the computed attribute values 263 | * from the first step {@link #initialize(nl.topicus.overheid.javafactorybot.Evaluator)}. 264 | * 265 | * This method is not used when {@link #build(M)} is called. 266 | * 267 | * @param attributes The computed attribute values of the object 268 | * @return A object with the values from the given attributes 269 | */ 270 | protected M construct(Map attributes) { 271 | getObjectType().newInstance(attributes) 272 | } 273 | 274 | /** 275 | * Third step of the build process. After the object is constructed, it is time for some fine-tuning before the object is 276 | * persisted (if we are creating the object) or returned as result. 277 | * 278 | * In this step, all onAfterBuild hooks are called. 279 | * 280 | * @param object The result of the second step ({@link #construct(java.util.Map)} 281 | * @param evaluator The evalutor to use in this step. 282 | * @return An object which is ready to be persisted or returned as result. 283 | */ 284 | protected M finalize(M object, Evaluator evaluator) { 285 | applyAfterBuildHooks(object, evaluator?.traits) 286 | } 287 | 288 | /** 289 | * Fourth step of the build process. If the object is build within a create context, this step will persist the object 290 | * to the data store. Otherwise, this step does nothing. 291 | * 292 | * @param object The object which should be persisted. Can be null 293 | * @param context The context which should be used to persist the object. 294 | * @return The persisted object of the same object. 295 | */ 296 | protected M persist(M object, FactoryContext context = null) { 297 | (context != null && object != null) ? context.persist(object) : object 298 | } 299 | 300 | /** 301 | * The fifth step of the build process. Some attribute values can only be created after the owner object is build. In this step, 302 | * these attributes are evaluated and combined with the object. 303 | * 304 | * @param object The build (and persisted) object 305 | * @param evaluator The evalutor to use in this step. 306 | * @return The object with additional attributes . 307 | */ 308 | protected M combine(M object, Evaluator evaluator) { 309 | Map attrs = evaluator.evaluateForFinalize(object) 310 | attrs.each { key, value -> object."$key" = value } 311 | object 312 | } 313 | 314 | // Private methods down here 315 | 316 | /** 317 | * Find a trait by name, and throw an exception if a trait with that name does not exist. 318 | */ 319 | protected Definition findTrait(String traitName) { 320 | Definition traitDefinition = getTraits()?.get(traitName) 321 | if (traitDefinition == null) throw new TraitNotFoundException(this, traitName) 322 | traitDefinition 323 | } 324 | 325 | /** 326 | * Apply all 'afterAttributes' hooks from factory and possible traits. 327 | */ 328 | private Map applyAfterAttributesHooks(Map attributes, List traits = null) { 329 | onAfterAttributes(attributes) 330 | if (traits) traits.each { findTrait(it).onAfterAttributes(attributes) } 331 | attributes 332 | } 333 | 334 | /** 335 | * Apply all 'afterBuild' hooks from factory and possible traits. 336 | */ 337 | private M applyAfterBuildHooks(M object, List traits = null) { 338 | onAfterBuild(object) 339 | if (traits) traits.each { findTrait(it).onAfterBuild(object) } 340 | object 341 | } 342 | 343 | /** 344 | * Execute the given closure in create context and return the result. 345 | */ 346 | private static T doInCreateContext(Closure closure) { 347 | FactoryManager.instance.enableCreateContext() 348 | def result = closure() 349 | FactoryManager.instance.disableCreateContext() 350 | result 351 | } 352 | } -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/Evaluator.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | import nl.topicus.overheid.javafactorybot.definition.Attribute 4 | import nl.topicus.overheid.javafactorybot.exception.EvaluationException 5 | 6 | /** 7 | * An evaluator takes a factory and the user specified overrides and yields the evaluated values of the attributes. 8 | */ 9 | class Evaluator { 10 | private Map attributes 11 | private Map overrides 12 | List traits 13 | private Map cache 14 | private BaseFactory factory 15 | 16 | Evaluator(BaseFactory factory, List traits, Map overrides) { 17 | this.factory = factory 18 | this.traits = traits 19 | this.overrides = overrides 20 | this.attributes = compileAttributes() 21 | this.cache = new HashMap<>() 22 | } 23 | 24 | /** 25 | * Gets all values for attributes which should be evaluated during the initialize step of the build process. 26 | * 27 | * This means that all attributes which are not flagged with afterBuild and all overrides which are not overriding after build attributes 28 | * should be evaluated. 29 | */ 30 | Map evaluateForInitialize() { 31 | Collection activeAttributeKeys = attributes.findAll { !it.value.afterBuild }.keySet() 32 | if (overrides != null) { 33 | activeAttributeKeys += (overrides.keySet() - attributes.findAll { it.value.afterBuild }.keySet()) 34 | } 35 | evaluateForKeys(activeAttributeKeys) 36 | } 37 | 38 | Map evaluateForFinalize(Object owner) { 39 | Collection activeAttributeKeys = attributes.findAll { it.value.afterBuild }.keySet() 40 | evaluateForKeys(activeAttributeKeys, owner) 41 | } 42 | 43 | Map evaluateForKeys(Collection keys, Object owner = null) { 44 | keys.inject([:], { Map result, String key -> result.put(key, get(key, owner)); result }) as Map 45 | } 46 | 47 | /** 48 | * Returns the evaluated value of a single attribute 49 | * @param name The name of the attribute to evaluate 50 | * @param owner The owner of the value of the attribute, if the owner is already build. 51 | * @return The evaluated value of the attribute 52 | */ 53 | def get(String name, Object owner = null) { 54 | if (!cache.containsKey(name)) { 55 | evaluate(name, owner) 56 | } 57 | 58 | return cache[name] 59 | } 60 | 61 | /** 62 | * Evaluates the attribute with the given name. Discards any value already in the cache. 63 | * @param name The name of the attribute to evaluate. 64 | * @param owner The owner of the value of the attribute, if the owner is already build. 65 | * @return The evaluated value. 66 | */ 67 | private def evaluate(String name, Object owner = null) { 68 | def attribute = attributes.get(name) 69 | if (attribute != null) { 70 | try { 71 | cache[name] = overrides != null && overrides.containsKey(name) ? attribute.evaluate(overrides[name], this, owner) : attribute.evaluate(this, owner) 72 | } catch (Exception e) { 73 | throw new EvaluationException(this, name, e) 74 | } 75 | } else if (overrides != null && overrides.containsKey(name)) { 76 | cache[name] = overrides[name] 77 | } else { 78 | throw new EvaluationException(this, name) 79 | } 80 | } 81 | 82 | /** 83 | * Compile the current list of traits into the base attributes 84 | * 85 | * @return A map of attributes including attributes from the traits. 86 | */ 87 | private Map compileAttributes() { 88 | if (traits != null && !traits.isEmpty()) { 89 | traits.inject(factory.attributes, { Map attributes, String traitName -> 90 | attributes + factory.findTrait(traitName).attributes 91 | }) as Map 92 | } else { 93 | factory.attributes 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/Factory.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | import com.github.javafaker.Faker 4 | 5 | /** 6 | * A factory is a special class which is able to generate new valid objects, for testing purposes. 7 | * These objects can be randomized by using a faker. This factory class uses the default faker from https://github.com/DiUS/java-faker. 8 | * 9 | * @param < M > The type of the generated object 10 | */ 11 | abstract class Factory extends BaseFactory { 12 | protected final Faker faker = new Faker() 13 | 14 | Faker getFaker() { 15 | faker 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/FactoryContext.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | /** 4 | * Interface for a context in which a factory should build objects. 5 | * Can be used to provide implementations for certain hooks in the process, for 6 | * example to persist the built object to a database. 7 | * 8 | * @author dennis 9 | * @since 04 Jan 2018 10 | */ 11 | interface FactoryContext { 12 | /** 13 | * Called when an object is build and should be persisted. 14 | *

15 | * This method will only be called when the object is non-null. 16 | * 17 | * @param object The object which was build. 18 | * @param The persisted object 19 | */ 20 | def M persist(M object) 21 | } 22 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/FactoryManager.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | import com.github.javafaker.Faker 4 | 5 | import java.lang.reflect.Method 6 | 7 | /** 8 | * Global manager for the factories which can be used to manage the factories. This manager is a singleton and can contain shared configuration 9 | * between factories. 10 | * 11 | * @author dennis 12 | * @since 04 Jan 2018 13 | */ 14 | @Singleton 15 | class FactoryManager { 16 | /** 17 | * Context which should be used as the current context when {@link BaseFactory#create} is used instead of {@link BaseFactory#build}. 18 | */ 19 | FactoryContext createContext = null 20 | 21 | /** 22 | * The context which should be used by the factories in the current execution. 23 | */ 24 | FactoryContext currentContext = null 25 | 26 | /** 27 | * Enable the create context. This method is called when one of the {@link BaseFactory#create} methods is used. By 28 | * setting the context only once, subsequent calls to {@link BaseFactory#build} which are part of the initial create 29 | * action will also result in presistent relations. 30 | */ 31 | void enableCreateContext() { 32 | currentContext = createContext 33 | } 34 | 35 | /** 36 | * Disable the create context. 37 | */ 38 | void disableCreateContext() { 39 | currentContext = null 40 | } 41 | 42 | private Map>, ? extends BaseFactory> factoryInstances = [:] 43 | 44 | /** 45 | * Gets or creates an instance of the given factory type. 46 | * 47 | * The default implementation keeps a single instance per factory type. A new instance is created 48 | * by calling {@link #newFactoryInstance(java.lang.Class)}}. 49 | * 50 | * @param factoryClass The type of the factory to get or create an instance of. 51 | * @return An instance of the factory type. 52 | */ 53 | def > T getFactoryInstance(Class factoryClass) { 54 | if (!factoryInstances.containsKey(factoryClass)) { 55 | factoryInstances.put(factoryClass, newFactoryInstance(factoryClass)) 56 | } 57 | factoryInstances[factoryClass as Class>] as T 58 | } 59 | 60 | /** 61 | * Creates a new instance of the given factory type. 62 | * 63 | * The default implementation looks if a method called 'getInstance' is defined on the class. If such 64 | * a method exists, this method is invoked. Otherwise, the default constructor is used. 65 | * 66 | * This implementation exists so the annotation {@link Singleton} can be applied to factories. 67 | * 68 | * @param factoryClass The type of the factory to create an instance of 69 | * @return A new instance of the factory type. 70 | */ 71 | def > T newFactoryInstance(Class factoryClass) { 72 | T factory = null 73 | try{ 74 | Method method = factoryClass.getMethod("getInstance") 75 | if(method != null){ 76 | factory = method.invoke(null) as T 77 | } 78 | } catch(NoSuchMethodException ignored) { 79 | // Do nothing 80 | } 81 | factory ?: factoryClass.newInstance() 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/AbstractFactoryAttribute.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import com.github.javafaker.Faker 4 | import nl.topicus.overheid.javafactorybot.BaseFactory 5 | import nl.topicus.overheid.javafactorybot.FactoryManager 6 | 7 | /** 8 | * Abstract class for attributes which are based on using another factory. 9 | */ 10 | abstract class AbstractFactoryAttribute { 11 | private Class> factoryClass 12 | private BaseFactory factory 13 | 14 | /** 15 | * Create a new instance. 16 | * 17 | * @param factory The factory to use for the associated object. 18 | */ 19 | AbstractFactoryAttribute(BaseFactory factory) { 20 | this.factory = factory 21 | } 22 | 23 | /** 24 | * Create a new instance. 25 | * 26 | * @param factoryClass The class of the factory to use for the associated object. 27 | * The factory itself is lazily initialized using {@link FactoryManager#getFactoryInstance(java.lang.Class)} 28 | */ 29 | AbstractFactoryAttribute(Class> factoryClass) { 30 | this.factoryClass = factoryClass 31 | } 32 | 33 | /** 34 | * Returns an instance of the factory. 35 | * This is either the specified instance, or a new instance which is created using {@link FactoryManager#getFactoryInstance(java.lang.Class)}. 36 | * 37 | * @return An instance of the factory. 38 | */ 39 | BaseFactory getFactory() { 40 | if (factory == null) { 41 | if (factoryClass != null) { 42 | factory = FactoryManager.instance.getFactoryInstance(factoryClass) 43 | } else { 44 | throw new IllegalArgumentException("Association defined without factory of factoryclass") 45 | } 46 | } 47 | factory 48 | } 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/Association.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import com.github.javafaker.Faker 4 | import nl.topicus.overheid.javafactorybot.BaseFactory 5 | import nl.topicus.overheid.javafactorybot.Evaluator 6 | import nl.topicus.overheid.javafactorybot.FactoryManager 7 | /** 8 | * Attribute used to define an association with another object, using a factory. A combination of the default overrides, 9 | * default object, traits and user specified overrides is used to create the associated object using the factory. 10 | * @param < T > The type of the associated object. 11 | */ 12 | class Association extends AbstractFactoryAttribute implements Attribute{ 13 | Closure> defaultOverridesProducer 14 | Closure defaultObjectProducer 15 | List traits 16 | boolean afterBuild = false 17 | 18 | /** 19 | * Create a new Association which combines user specified overrides with optional default overrides and traits. 20 | * @param factory The factory to use for the associated object. 21 | * @param defaultOverrides Default overrides to pass to the factory. Can be overriden by user specified overrides. 22 | * @param traits List of traits to apply to the associated object. 23 | */ 24 | Association(BaseFactory factory) { 25 | super(factory) 26 | } 27 | 28 | /** 29 | * Create a new Association which combines user specified overrides with optional default overrides and traits. 30 | * @param factoryClass The class of the factory to use for the associated object. 31 | * The factory itself is lazily initialized using {@link FactoryManager#getFactoryInstance(java.lang.Class)} 32 | * @param defaultOverrides Default overrides to pass to the factory. Can be overriden by user specified overrides. 33 | * @param traits List of traits to apply to the associated object. 34 | */ 35 | Association(Class> factoryClass) { 36 | super(factoryClass) 37 | } 38 | 39 | @Override 40 | def evaluate(Evaluator evaluator, Object owner) { 41 | if (defaultOverridesProducer != null) { 42 | // Build using the default overrides 43 | getFactory().build(defaultOverridesProducer(owner), traits) 44 | } else if (defaultObjectProducer != null) { 45 | // Build using the default object 46 | getFactory().build(defaultObjectProducer()) 47 | } else { 48 | // Default build 49 | traits ? getFactory().build(traits) : getFactory().build() 50 | } 51 | } 52 | 53 | @Override 54 | def evaluate(Object override, Evaluator evaluator, Object owner) { 55 | if (override == null || override instanceof T) { 56 | getFactory().build((T) override) 57 | } else if (override instanceof Map) { 58 | // override given as map, use these together with default overrides to build the object 59 | getFactory().build(defaultOverridesProducer ? defaultOverridesProducer(owner) + override : override, traits) 60 | } else { 61 | throw new IllegalArgumentException("Override should be null, a Map or an object of the associated type") 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/Attribute.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import nl.topicus.overheid.javafactorybot.Evaluator 4 | 5 | /** 6 | * Interface of a definition of an attribute of an object. An Attribute is responsible for generating the value of the 7 | * attribute, taking into account the user specified override and evaluator. The evaluator can be used to determine 8 | * values of other attributes. 9 | */ 10 | interface Attribute extends GroovyObject { 11 | /** 12 | * Get the value of this attribute, possibly using the given evaluator. 13 | * 14 | * @param evaluator The evaluator which can be used to determine the value of other attribute. 15 | * @param owner The owner of the value of the attribute, if the owner is already build. 16 | * @return The value of this attribute. 17 | */ 18 | def evaluate(Evaluator evaluator, Object owner) 19 | 20 | /** 21 | * Get the value of this attribute using the given override, possibly using the given evaluator. 22 | * 23 | * @param override The override for this attribute, as given by the user. This can be intentionally null, for 24 | * instance when the value of the attribute should be null. If no override is given {@link #evaluate(Evaluator, Object)} 25 | * is used instead. 26 | * @param evaluator The evaluator which can be used to determine the value of other attribute. 27 | * @param owner The owner of the value of the attribute, if the owner is already build. 28 | * @return The value of this attribute. 29 | */ 30 | def evaluate(Object override, Evaluator evaluator, Object owner) 31 | 32 | /** 33 | * Determines if this attribute should be evaluated before or after the owner object is build. 34 | * 35 | * If the result is {@code false}, the attribute will be evaluated during the initialize build step (in which attributes are build). 36 | * If the result is {@code true}, the attribute will be evaluated during the combine build step (after persist). 37 | * @return If the attribute should be evaluated after the owner object is build. 38 | */ 39 | boolean isAfterBuild() 40 | } 41 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/Definition.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import nl.topicus.overheid.javafactorybot.factory.FactoryAttributes 4 | import nl.topicus.overheid.javafactorybot.factory.FactoryDSL 5 | import nl.topicus.overheid.javafactorybot.factory.FactoryHooks 6 | import nl.topicus.overheid.javafactorybot.factory.FactoryTraits 7 | 8 | /** 9 | * A definition is the base class containing the definition of how an object should be created. This base is used by 10 | * both the factory and traits, to allow to use the same syntax for both. 11 | */ 12 | class Definition implements FactoryHooks, FactoryAttributes, FactoryDSL, FactoryTraits { 13 | } 14 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/ManyAssociation.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import com.github.javafaker.Faker 4 | import nl.topicus.overheid.javafactorybot.BaseFactory 5 | import nl.topicus.overheid.javafactorybot.Evaluator 6 | 7 | /** 8 | * Attribute used to define an association with a list of objects, using a factory. 9 | * A combination of the default overrides, default object, traits and user specified overrides is used to create the 10 | * associated object using the factory. 11 | * @param < T > The type of the associated object. 12 | */ 13 | class ManyAssociation extends AbstractFactoryAttribute implements Attribute { 14 | Closure> generalOverridesProvider 15 | List overrides 16 | int amount 17 | List traits 18 | boolean afterBuild = false 19 | Closure transform = null 20 | 21 | /** 22 | * Create a new Association which combines user specified overrides with optional default overrides and traits. 23 | * @param factory The factory to use for the associated object. 24 | * @param defaultOverrides Default overrides to pass to the factory. Can be overriden by user specified overrides. 25 | * @param traits List of traits to apply to the associated object. 26 | */ 27 | ManyAssociation(BaseFactory factory) { 28 | super(factory) 29 | } 30 | 31 | /** 32 | * Create a new Association which combines user specified overrides with optional default overrides and traits. 33 | * @param factoryClass The class of the factory to use for the associated object. 34 | * The factory itself is lazily initialized using {@link nl.topicus.overheid.javafactorybot.FactoryManager#getFactoryInstance(java.lang.Class)}. 35 | * @param defaultOverrides Default overrides to pass to the factory. Can be overriden by user specified overrides. 36 | * @param traits List of traits to apply to the associated object. 37 | */ 38 | ManyAssociation(Class> factoryClass) { 39 | super(factoryClass) 40 | } 41 | 42 | @Override 43 | def evaluate(Evaluator evaluator, Object owner) { 44 | def result 45 | 46 | if (overrides != null) { 47 | result = getFactory().buildList(compileListOverride(overrides, owner)) 48 | } else if (generalOverridesProvider != null) { 49 | result = getFactory().buildList(amount, generalOverridesProvider(owner)) 50 | } else { 51 | result = getFactory().buildList(amount) 52 | } 53 | 54 | transform ? transform(result) : result 55 | } 56 | 57 | @Override 58 | def evaluate(Object override, Evaluator evaluator, Object owner) { 59 | def result 60 | 61 | if (override instanceof List) { 62 | result = getFactory().buildList(compileListOverride(override, owner)) 63 | } else if (override instanceof Integer) { 64 | // Build the given amount of object 65 | result = getFactory().buildList(override) 66 | } else { 67 | throw new IllegalArgumentException("Override for a toMany association should be an integer (amount) " + 68 | "or a list containing individual overrides/objects. " + 69 | "Instead, an instance of type ${override.getClass().name} was received.") 70 | } 71 | 72 | transform ? transform(result) : result 73 | } 74 | 75 | List compileListOverride(List override, Object owner) { 76 | // A list is given. Each element in the list should be either a map with overrides, or an object (or null) 77 | // If it is a map, we merge it with the default overrides, just as we do with single associations 78 | override.collect { it instanceof Map && generalOverridesProvider ? generalOverridesProvider(owner) + it : it } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/Trait.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | class Trait extends Definition { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/definition/ValueAttribute.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.definition 2 | 3 | import groovy.transform.stc.ClosureParams 4 | import groovy.transform.stc.SimpleType 5 | import nl.topicus.overheid.javafactorybot.Evaluator 6 | /** 7 | * Attribute which has a single value. The value is either the user specified override, or the result of the given 8 | * value generator closure. 9 | */ 10 | class ValueAttribute implements Attribute { 11 | private Closure defaultValueGenerator 12 | boolean afterBuild = false 13 | 14 | /** 15 | * Create a new ValueAttribute which yields the result of the given closure when no override is specified, or the 16 | * override otherwise. 17 | * @param defaultValueGenerator The closure of which the result is yielded when no override is speicified. 18 | */ 19 | ValueAttribute( 20 | @DelegatesTo(Evaluator) @ClosureParams(value = SimpleType, options = "Evaluator") Closure defaultValueGenerator, boolean afterBuild = false) { 21 | this.defaultValueGenerator = defaultValueGenerator 22 | this.afterBuild = afterBuild 23 | } 24 | 25 | @Override 26 | def evaluate(Evaluator evaluator, Object owner) { 27 | defaultValueGenerator.delegate = evaluator 28 | defaultValueGenerator(evaluator) 29 | } 30 | 31 | @Override 32 | def evaluate(Object override, Evaluator evaluator, Object owner) { 33 | override 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/exception/EvaluationException.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.exception 2 | 3 | import nl.topicus.overheid.javafactorybot.Evaluator 4 | 5 | class EvaluationException extends IllegalStateException { 6 | EvaluationException(Evaluator evaluator, String attributeName, Exception cause = null) { 7 | super("Unable to evaluate attribute '$attributeName' for factory ${evaluator.factory.class.simpleName}: ${cause?.message}", cause) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/exception/TraitNotFoundException.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.exception 2 | 3 | import nl.topicus.overheid.javafactorybot.BaseFactory 4 | 5 | class TraitNotFoundException extends IllegalStateException { 6 | TraitNotFoundException(BaseFactory factory, String traitName) { 7 | super("Trait '$traitName' is not specified on ${factory.class.simpleName}. Specified traits are: ${factory.traits ?: "none"}") 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/factory/FactoryAttributes.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.factory 2 | 3 | 4 | import nl.topicus.overheid.javafactorybot.definition.Attribute 5 | 6 | trait FactoryAttributes { 7 | /** 8 | * Map containing {@link Attribute}s of this factory. An {@link Attribute} is a definition of an attribute in the 9 | * (generated) object, and minimally implements a function which, given an instance of {@link nl.topicus.overheid.javafactorybot.Evaluator}, yields the 10 | * value this attribute should have in the generated object. 11 | * 12 | * @return A map containing the {@link Attribute}s of this factory. 13 | */ 14 | Map attributes = [:] 15 | } 16 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/factory/FactoryDSL.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.factory 2 | 3 | import com.github.javafaker.Faker 4 | import groovy.transform.stc.ClosureParams 5 | import groovy.transform.stc.SimpleType 6 | import nl.topicus.overheid.javafactorybot.BaseFactory 7 | import nl.topicus.overheid.javafactorybot.Evaluator 8 | import nl.topicus.overheid.javafactorybot.definition.Association 9 | import nl.topicus.overheid.javafactorybot.definition.ManyAssociation 10 | import nl.topicus.overheid.javafactorybot.definition.ValueAttribute 11 | 12 | /** 13 | * Trait containing methods which aid in defining a factory. 14 | */ 15 | trait FactoryDSL { 16 | /** 17 | * Defines an attribute which either uses the user specified override or the result of the closure. 18 | * 19 | * @param defaultValueGenerator The closure which generates a value when no override is given. 20 | * @return An attribute which resolves to the override or the result of the closure. 21 | */ 22 | ValueAttribute value(@DelegatesTo(Evaluator) @ClosureParams(value = SimpleType, options = "Evaluator") Closure defaultValueGenerator) { 23 | new ValueAttribute(defaultValueGenerator) 24 | } 25 | 26 | /** 27 | * Defines a relationship with a single object. 28 | * 29 | * @param factoryClass The type of the factory which should be used to generate the related object. 30 | * @return An association capable of generating the related object. 31 | */ 32 | def Association hasOne(Class> factoryClass) { 33 | new Association<>(factoryClass) 34 | } 35 | 36 | /** 37 | * Defines a relationship with a single object. 38 | * 39 | * @param factory The factory which should be used to generate the related object. 40 | * @return An association capable of generating the related object. 41 | */ 42 | def Association hasOne(BaseFactory factory) { 43 | new Association<>(factory) 44 | } 45 | 46 | /** 47 | * Defines a relationship with a single object. 48 | * 49 | * @param options A map containing options for the relationship. Possible options: 50 | *
    51 | *
  • default : {@link Closure} - A closure which yields the default object to be used.
  • 52 | *
  • overrides : {@link Map}|{@link Closure} - A map of default overrides, or a closure yielding the default overrides. 53 | * Combined with the user specified overrides, they form the overrides given to the factory. If this relationship is evaluated after the main 54 | * object, the closure is called with the created owner.
  • 55 | *
  • traits : {@link List} - A list of names of traits to apply by default
  • 56 | *
  • afterBuild : {@link Boolean} - Determines if this relationship is evaluated before the object is constructed, or after 57 | * it is created. Defaults to false.
  • 58 | *
59 | * @param factoryClass The type of the factory which should be used to generate the related object. 60 | * @return An association capable of generating the related object. 61 | */ 62 | def Association hasOne(Map options, Class> factoryClass) { 63 | Association association = new Association(factoryClass) 64 | parseHasOneOptions(association, options) 65 | association 66 | } 67 | 68 | /** 69 | * Defines a relationship with a single object. 70 | * 71 | * @param options A map containing options for the relationship. Possible options: 72 | *
    73 | *
  • default : {@link Closure} - A closure which yields the default object to be used.
  • 74 | *
  • overrides : {@link Map}|{@link Closure} - A map of default overrides, or a closure yielding the default overrides. 75 | * Combined with the user specified overrides, they form the overrides given to the factory. If this relationship is evaluated after the main 76 | * object, the closure is called with the created owner.
  • 77 | *
  • traits : {@link List} - A list of names of traits to apply by default
  • 78 | *
  • afterBuild : {@link Boolean} - Determines if this relationship is evaluated before the object is constructed, or after 79 | * it is created. Defaults to false.
  • 80 | *
81 | * @param factory The factory which should be used to generate the related object. 82 | * @return An association capable of generating the related object. 83 | */ 84 | def Association hasOne(Map options, BaseFactory factory) { 85 | Association association = new Association(factory) 86 | parseHasOneOptions(association, options) 87 | association 88 | } 89 | 90 | /** 91 | * Defines a relationship with multiple objects. 92 | * 93 | * @param factoryClass The type of the factory which should be used to generate the related objects. 94 | * @return An association capable of generating the related objects. 95 | */ 96 | def ManyAssociation hasMany(Class> factoryClass) { 97 | new ManyAssociation(factoryClass) 98 | } 99 | 100 | /** 101 | * Defines a relationship with multiple objects. 102 | * 103 | * @param factory The factory which should be used to generate the related objects. 104 | * @return An association capable of generating the related objects. 105 | */ 106 | def ManyAssociation hasMany(BaseFactory factory) { 107 | new ManyAssociation(factory) 108 | } 109 | 110 | /** 111 | * Defines a relationship with multiple objects. 112 | * 113 | * @param options A map containing options for the relationship. Possible options: 114 | *
    115 | *
  • overrides : {@link List} - A list containing overrides (maps) or the related objects which should be used by the factory.
  • 116 | *
  • generalOverrides : {@link Map}|{@link Closure} - A map of default overrides, or a closure yielding the default overrides. 117 | * Combined with the user specified overrides, they form the overrides given to the factory. If this relationship is evaluated after the main 118 | * object, the closure is called with the created owner.
  • 119 | *
  • traits : {@link List} - A list of names of traits to apply by default
  • 120 | *
  • afterBuild : {@link Boolean} - Determines if this relationship is evaluated before the object is constructed, or after 121 | * it is created. Defaults to false.
  • 122 | *
  • amount : {@link Integer} - The number of related objects to generate, if no other amount or list of overrides is specified.
  • 123 | *
  • transform : {@link Closure} - A closure which gets the generated list of related objects and returns a transformed collection. 124 | * This can be useful if the final collection should not be a list but any other type, like a set.
  • 125 | *
126 | * @param factoryClass The type of the factory which should be used to generate the related objects. 127 | * @return An association capable of generating the related objects. 128 | */ 129 | def ManyAssociation hasMany(Map options, Class> factoryClass) { 130 | def association = new ManyAssociation(factoryClass) 131 | parseHasManyOptions(association, options) 132 | association 133 | } 134 | 135 | /** 136 | * Defines a relationship with multiple objects. 137 | * 138 | * @param options A map containing options for the relationship. Possible options: 139 | *
    140 | *
  • overrides : {@link List} - A list containing overrides (maps) or the related objects which should be used by the factory.
  • 141 | *
  • generalOverrides : {@link Map}|{@link Closure} - A map of default overrides, or a closure yielding the default overrides. 142 | * Combined with the user specified overrides, they form the overrides given to the factory. If this relationship is evaluated after the main 143 | * object, the closure is called with the created owner.
  • 144 | *
  • traits : {@link List} - A list of names of traits to apply by default
  • 145 | *
  • afterBuild : {@link Boolean} - Determines if this relationship is evaluated before the object is constructed, or after 146 | * it is created. Defaults to false.
  • 147 | *
  • amount : {@link Integer} - The number of related objects to generate, if no other amount or list of overrides is specified.
  • 148 | *
  • transform : {@link Closure} - A closure which gets the generated list of related objects and returns a transformed collection. 149 | * This can be useful if the final collection should not be a list but any other type, like a set.
  • 150 | *
151 | * @param factory The factory which should be used to generate the related objects. 152 | * @return An association capable of generating the related objects. 153 | */ 154 | def ManyAssociation hasMany(Map options, BaseFactory factory) { 155 | def association = new ManyAssociation(factory) 156 | parseHasManyOptions(association, options) 157 | association 158 | } 159 | 160 | private def parseHasOneOptions(Association association, Map args) { 161 | association.defaultObjectProducer = args['default'] as Closure 162 | def defaultOverrides = args['overrides'] 163 | if (defaultOverrides instanceof Closure) { 164 | association.defaultOverridesProducer = defaultOverrides 165 | } else { 166 | association.defaultOverridesProducer = defaultOverrides ? { defaultOverrides as Map } : null 167 | } 168 | association.traits = args['traits'] as List 169 | association.afterBuild = (args['afterBuild'] ?: false) as boolean 170 | } 171 | 172 | private def parseHasManyOptions(ManyAssociation association, Map args) { 173 | association.overrides = args['overrides'] as List 174 | def generalOverrides = args['generalOverrides'] 175 | if (generalOverrides instanceof Closure) { 176 | association.generalOverridesProvider = generalOverrides 177 | } else { 178 | association.generalOverridesProvider = generalOverrides ? { generalOverrides as Map } : null 179 | } 180 | association.traits = args['traits'] as List 181 | association.afterBuild = (args['afterBuild'] ?: false) as boolean 182 | association.amount = (args['amount'] ?: 0) as int 183 | association.transform = args['transform'] as Closure 184 | } 185 | } -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/factory/FactoryHooks.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.factory 2 | 3 | trait FactoryHooks { 4 | /** 5 | * Callback which is called after the values of the attributes are evaluated, but before the object itself is built. 6 | * 7 | * @param attributes The evaluated attributes 8 | */ 9 | void onAfterAttributes(Map attributes) { 10 | } 11 | 12 | /** 13 | * Callback which is called after the model is built using the evaluated attributes, but before it is returned as 14 | * result of the build() method. This allows to tweak the model, for example to fix relationships. 15 | * 16 | * @param model The model after it was built using the evaluated attributes. Can be null 17 | */ 18 | void onAfterBuild(M model) { 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/groovy/nl/topicus/overheid/javafactorybot/factory/FactoryTraits.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.factory 2 | 3 | import nl.topicus.overheid.javafactorybot.definition.Trait 4 | 5 | trait FactoryTraits { 6 | /** 7 | * Returns a map containing possible traits for this factory. A trait is a collection of attributes and relations, 8 | * meant to put the generated object in a certain state. A trait is identified by a name, 9 | * while the trait itself is declared as a Closure over the generated object. 10 | * 11 | * Traits are applied after the object is build from attributes, but before {@link FactoryHooks#onAfterBuild(java.lang.Object)} 12 | * is called. 13 | * 14 | * @return A map from trait name to trait function of possible traits for this factory. 15 | * @see Traits applied in ruby factories 16 | */ 17 | Map> getTraits() { 18 | null 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/groovy/nl/topicus/overheid/javafactorybot/BaseFactoryTest.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot 2 | 3 | import nl.topicus.overheid.javafactorybot.test.factory.ArticleFactory 4 | import nl.topicus.overheid.javafactorybot.test.model.Article 5 | import nl.topicus.overheid.javafactorybot.test.model.User 6 | import spock.lang.Specification 7 | import spock.lang.Subject 8 | 9 | class BaseFactoryTest extends Specification { 10 | @Subject 11 | ArticleFactory factory = new ArticleFactory() 12 | 13 | def "it fills the attributes when no overrides are given"() { 14 | when: 15 | Article article = new ArticleFactory().build() 16 | 17 | then: "defined attributes with default are filled" 18 | article.title != null 19 | article.content != null 20 | article.creationDate != null 21 | 22 | and: "defined attributes with default null are null" 23 | article.summary == null 24 | 25 | and: "relations are set" 26 | article.author != null 27 | article.author instanceof User 28 | article.comments != null 29 | article.comments.size() == 0 30 | 31 | and: "nondefined attributes are not filled" 32 | article.slug == null 33 | } 34 | 35 | def "it uses overrides"() { 36 | when: 37 | Article article = factory.build([title: "foo", slug: "derp"]) 38 | 39 | then: "overrides are used" 40 | article.title == "foo" 41 | article.slug == "derp" 42 | 43 | and: "remaining attributes are filled as default" 44 | article.content != null 45 | article.creationDate != null 46 | article.summary == null 47 | article.author != null 48 | article.author instanceof User 49 | article.comments != null 50 | article.comments.size() == 0 51 | } 52 | 53 | def "when creating the create context is used"() { 54 | given: 55 | FactoryContext createContext = Mock(FactoryContext) 56 | FactoryManager.instance.createContext = createContext 57 | 58 | when: 59 | Article article = new ArticleFactory().create() 60 | 61 | then: 62 | 1 * createContext.persist(_ as User) >> { User a -> a } 63 | 1 * createContext.persist(_ as Article) >> { Article a -> a } 64 | article != null 65 | 66 | then: "defined attributes with default are filled" 67 | article.title != null 68 | article.content != null 69 | article.creationDate != null 70 | 71 | and: "defined attributes with default null are null" 72 | article.summary == null 73 | 74 | and: "relations are set" 75 | article.author != null 76 | article.author instanceof User 77 | article.comments != null 78 | article.comments.size() == 0 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/groovy/nl/topicus/overheid/javafactorybot/test/factory/ArticleFactory.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.factory 2 | 3 | import nl.topicus.overheid.javafactorybot.Factory 4 | import nl.topicus.overheid.javafactorybot.definition.Attribute 5 | import nl.topicus.overheid.javafactorybot.definition.Trait 6 | import nl.topicus.overheid.javafactorybot.test.model.Article 7 | 8 | import java.util.concurrent.TimeUnit 9 | 10 | class ArticleFactory extends Factory
{ 11 | Map attributes = [ 12 | title : value { faker.lorem().sentence() }, 13 | content : value { faker.lorem().paragraph() }, 14 | creationDate: value { faker.date().past(20, TimeUnit.DAYS) }, 15 | summary : value { null }, 16 | author : hasOne(UserFactory), 17 | comments : hasMany(CommentFactory, afterBuild: true, defaultOverrides: { Article it -> [article: it] }) 18 | ] 19 | 20 | Map traits = [ 21 | withComments: new WithCommentsTrait() 22 | ] 23 | 24 | class WithCommentsTrait extends Trait
{ 25 | Map attributes = [ 26 | comments: hasMany(CommentFactory, amount: 3) 27 | ] 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/groovy/nl/topicus/overheid/javafactorybot/test/factory/CommentFactory.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.factory 2 | 3 | import nl.topicus.overheid.javafactorybot.Factory 4 | import nl.topicus.overheid.javafactorybot.definition.Attribute 5 | import nl.topicus.overheid.javafactorybot.test.model.Comment 6 | 7 | import java.util.concurrent.TimeUnit 8 | 9 | class CommentFactory extends Factory { 10 | Map attributes = [ 11 | article : hasOne(ArticleFactory), 12 | author : hasOne(UserFactory), 13 | content : value { faker.lorem().paragraph() }, 14 | creationDate: value { faker.date().past(20, TimeUnit.DAYS) } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /src/test/groovy/nl/topicus/overheid/javafactorybot/test/factory/UserFactory.groovy: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.factory 2 | 3 | import nl.topicus.overheid.javafactorybot.Factory 4 | import nl.topicus.overheid.javafactorybot.definition.Attribute 5 | import nl.topicus.overheid.javafactorybot.test.model.User 6 | 7 | class UserFactory extends Factory { 8 | Map attributes = [ 9 | username : value { faker.name().username() }, 10 | firstName: value { faker.name().firstName() }, 11 | lastName : value { faker.name().lastName() }, 12 | email : value { "${get("firstName")}.${get("lastName")}@example.com" } 13 | ] 14 | } -------------------------------------------------------------------------------- /src/test/java/nl/topicus/overheid/javafactorybot/test/model/Article.java: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | @Data 9 | public class Article { 10 | // Attributes 11 | private String title; 12 | private String content; 13 | private Date creationDate; 14 | private String slug; 15 | private String summary; 16 | 17 | // Relations 18 | private User author; 19 | private List comments; 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/nl/topicus/overheid/javafactorybot/test/model/Comment.java: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Date; 6 | 7 | @Data 8 | public class Comment { 9 | private Article article; 10 | private User author; 11 | private String content; 12 | private Date creationDate; 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/nl/topicus/overheid/javafactorybot/test/model/User.java: -------------------------------------------------------------------------------- 1 | package nl.topicus.overheid.javafactorybot.test.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class User { 7 | private String username; 8 | private String firstName; 9 | private String lastName; 10 | private String email; 11 | } 12 | --------------------------------------------------------------------------------