Brings the popular ruby faker gem to Java and Kotlin

Related tags

Testing testing faker
Overview

Data Faker

Maven Status License Coverage Status

This library is a modern port of java-faker, built on Java 8, with up to date libraries and several newly added Fake Generators.

This library generates fake data, similar to other fake data generators, such as:

It's useful when you're developing a new project and need some pretty data for showcase.

Usage

In the pom.xml, add the following fragment to the dependencies section:

<dependency>
    <groupId>net.datafaker</groupId>
    <artifactId>datafaker</artifactId>
    <version>1.1.0</version>
</dependency>

For Gradle users, add the following to your build.gradle file.

dependencies {
    implementation 'net.datafaker:datafaker:1.1.0'
}

In your Java code:

Faker faker = new Faker();

String name = faker.name().fullName(); // Miss Samanta Schmidt
String firstName = faker.name().firstName(); // Emory
String lastName = faker.name().lastName(); // Barton

String streetAddress = faker.address().streetAddress(); // 60018 Sawayn Brooks Suite 449

Or in your Kotlin code:

val faker = Faker()

val name = faker.name().fullName() // Miss Samanta Schmidt
val firstName = faker.name().firstName() // Emory
val lastName = faker.name().lastName() // Barton

val streetAddress = faker.address().streetAddress() // 60018 Sawayn Brooks Suite 449

This is a demo web application that uses the library.

Javadoc

https://www.datafaker.net/docs

Contributions

See CONTRIBUTING.md

Providers

  • Address
  • Ancient
  • Animal
  • App
  • Appliance ()
  • Aqua Teen Hunger Force
  • Artist
  • Avatar
  • Aviation
  • Babylon5 ()
  • Back To The Future
  • Barcode ()
  • Basketball
  • Beer
  • Bojack Horseman
  • Book
  • Bool
  • Bossa Nova ()
  • Breaking Bad ()
  • Business
  • CNPJ Brazilian National Registry of Legal Entities
  • CPF Brazilian individual taxpayer registry identification
  • Cat
  • ChuckNorris
  • Code
  • Coin
  • Color
  • Commerce
  • Company
  • Crypto
  • DateAndTime
  • Demographic
  • Dessert ()
  • Disease
  • Dog
  • Domain ()
  • DragonBall
  • Dune
  • Durations ()
  • Educator
  • EnglandFootBall ()
  • Esports
  • File
  • Finance
  • Food
  • Friends
  • FunnyName
  • GameOfThrones
  • Gender
  • Hacker
  • HarryPotter
  • Heartstone ()
  • Hipster
  • HitchhikersGuideToTheGalaxy
  • Hobbit
  • HowIMetYourMother
  • IdNumber
  • Internet
  • Job
  • Kaamelott
  • LeagueOfLegends
  • Lebowski
  • LordOfTheRings
  • Lorem
  • Matz
  • Minecraft ()
  • Mood ()
  • Mountains ()
  • Music
  • Name
  • Nation
  • Number
  • Options
  • Overwatch
  • Passport ()
  • PhoneNumber
  • Photography
  • Pokemon
  • Princess Bride
  • Relationship Terms
  • Resident Evil ()
  • RickAndMorty
  • Robin
  • RockBand
  • RuPaul's Drag Race ()
  • Shakespeare
  • Sip
  • SlackEmoji
  • Space
  • StarCraft
  • StarTrek
  • Stock
  • Superhero
  • Team
  • Touhou ()
  • TwinPeaks
  • Twitter ()
  • University
  • Vehicle ()
  • Weather
  • Witcher
  • Yoda
  • Zelda

Usage with Locales

Faker faker = new Faker(new Locale("YOUR_LOCALE"));

For example:

new Faker(new Locale("en-us")).address().zipCodeByState("CA"));

Supported Locales

  • ar
  • bg
  • ca
  • ca-CAT
  • cs
  • da-DK
  • de
  • de-AT
  • de-CH
  • en
  • en-AU
  • en-au-ocker
  • en-BORK
  • en-CA
  • en-GB
  • en-IND
  • en-MS
  • en-NEP
  • en-NG
  • en-NZ
  • en-PAK
  • en-SG
  • en-UG
  • en-US
  • en-ZA
  • es
  • es-MX
  • fa
  • fi-FI
  • fr
  • he
  • hu
  • in-ID
  • it
  • ja
  • ko
  • nb-NO
  • nl
  • pl
  • pt
  • pt-BR
  • ru
  • sk
  • sv
  • sv-SE
  • tr
  • uk
  • vi
  • zh-CN
  • zh-TW

LICENSE

Copyright (c) 2022 DataFaker.net See the LICENSE file for license rights and limitations.

Comments
  • Architectural changes creating either modules or abstractions for the generators

    Architectural changes creating either modules or abstractions for the generators

    Context

    This is an excellent fork from JavaFaker that adds everything that the project commuters aren't approving. Most of the requests are either improving the library or adding new generators.

    Problem state

    One of the problems from the fork is that we got a lot of "not so focused and useful" generators, as a lot of movies something (in JavaFaker almost of half generators are movie-related).

    Proposition

    Either create modules for those kinds of generators (movies, for example) or the creation of one more abstraction layer to group different generators.

    New Module

    It would be a new library that can be added on the top of the main one. For example:

    Main library with "most important generators"

    <dependency>
        <groupId>net.datafaker</groupId>
        <artifactId>datafaker</artifactId>
        <version>1.3.0</version>
    </dependency>
    

    Library extension

    <dependency>
        <groupId>net.datafaker</groupId>
        <artifactId>datafaker-movies-module</artifactId>
        <version>1.0.0</version>
    </dependency>
    

    Pros

    • See only generators that make sense in some context
    • Isolation during development, fixes, and releases
    • Centralized contributions

    Cons

    • Hard to define the "most important generators"
    • Possible changes in the current architecture
    • Different places to maintain, as most of the generators would be modules
    • Breaking change added for this adoption
    • Time-consuming to implement

    New abstraction

    It consists of the addition of one more object during the Fluent Interface usage, like:

    faker.medical().bloodType()...
    faker.business().creditCardType()...
    faker.movies().avatar()...
    faker.personal().address()...
    faker.sports().formula1()...
    

    Pros

    • Beter code usage from the consumer side, there it can focus on finding and using the generators
    • More consistent architecture
    • Code isolation

    Cons

    • Breaking change added for this adoption

    Benefits

    Also, in a corporate world, it's sad trying to use a generator and see a lot of those generators.

    Final comments

    I believe that the adoption of one of the approaches will bring benefits to this project. And I am open to helping in the implementation.

    opened by eliasnogueira 29
  • Generate boolean with probability

    Generate boolean with probability

    Add ability to generate boolean value with some predefined probability of true

    Example:

    Faker faker = new Faker().withProbabilityConfig(new ProbabilityConfig().withBool(0.0));
    boolean falseValue = faker.bool().bool(); // always false
    
    faker = faker.withProbabilityConfig(new ProbabilityConfig().withBool(1.0));
    boolean trueValue = faker.bool().bool(); // always true
    
    faker = faker.withProbabilityConfig(new ProbabilityConfig().withBool(0.7));
    boolean value = faker.bool().bool(); // will generate true with probability 70 % and false with probability 30 %
    
    opened by NarekDW 23
  • Data generation repeatability and Faker attribute access

    Data generation repeatability and Faker attribute access

    Is your feature request related to a problem? Please describe. In order to support data generation repeatability, it is important to be able to easily set the Random seed. Currently, the Faker constructor signatures make this a difficult task when a Faker uses another Faker internally.

    Faker A should be able to easily pass along its Random when constructing Faker B. While you can get access to the RandomService, you cannot easily obtain the Random object within it. Using the RandomService to construct Faker B then requires other parameters to do so.

    A similar problem exists with Locales last I recall, where it is difficult to access the current configuration of a given Faker.

    Describe the solution you'd like Attributes like Random and Locale should be accessible after a given Fake is constructed. This would improve the ability to utilize Faker's internally within other fakers, and help to improve logging capabilities where it might be important to trace some of these elements for test repeatability.

    opened by jpeffer 23
  • POC for faker splitting

    POC for faker splitting

    This is a kind of POC for the issue mentioned at https://github.com/datafaker-net/datafaker/issues/157. The PR attempts to introduce faker specific interfaces like BaseFaker, MovieFaker, SportFaker, VideoGameFaker. It allows to have for a specific faker only a limited set of providers. At the same time for user there is almost nothing changed(old api still works) e.g.

    BaseFaker baseFaker = new Faker();
    SportFaker sportFaker = new Faker();
    VideoGameFaker videogameFaker = new Faker();
    MoviewFaker moviewFaker = new Faker(); 
    Faker fullFaker = new Faker();
    

    IDE will continue show hints for available methods however for sport faker it will show only sport and base methods, for movie it will show only movie and base related methods, for fullFaker it will show all and etc. In case there is an entity which is potentially could be in several groups then with interface it is not an issue.

    @bodiam @jpeffer @eliasnogueira since you were involved in https://github.com/datafaker-net/datafaker/issues/157 WDYT?

    opened by snuyanzin 22
  • Improve the quality of phone numbers generated

    Improve the quality of phone numbers generated

    At the moment, the quality of some generated phone numbers is quite poor. To demonstrate this, there's a test called PhoneNumberValidityFinderTest.testAllPhoneNumbers, which generates the following output:

    en_NZ=53
    fr_CH=57
    lv_LV=60
    pt_PT=66
    en_MS=69
    tr_TR=84
    zh_CN=86
    hu_HU=93
    en_PH=93
    by_BY=94
    ar_AR=97
    no_NO=99
    zh_TW=100
    sv_SV=100
    es_AR=100
    bg_BG=100
    

    This means that for the locales zh_TW, sv_SV, es_AR and bg_BG currently all phone numbers are generated incorrectly.

    It would be great if we can improve the quality here a little bit.

    opened by bodiam 21
  • FakeStream implementation

    FakeStream implementation

    This is the FakeStream simple implementation. But I have a few doubts here:

    1. Is it worth to move FakeStream and FakeCollection classes to separate folder (like util) ?
    2. For now it doesn't support operations like Format.toCsv(FakeStream.Builder...) and Format.toJson(FakeStream.Builder...) as it (Csv and Json classes in particular) was designed for FakeCollection only and it will take much effort (and much redundant and similar code) to add such an ability. What do you think, how could we improve the code and avoid of writing a lot of similar code? Probably to add some new level of abstraction? Or adding some converter function, which could convert FakeStream to FakeCollection and the pass collection to the functions like Format.toCsv(FakeStream.Builder...) and Format.toJson(FakeStream.Builder...) ?
    3. Also, do we need a common interface or abstract class for FakeCollection and FakeStream, as them contain quite similar API? From my point of view, here we don't need common interface, as in fact them belong to different subjects...
    opened by NarekDW 16
  • Support extensible model to register custom external faker service

    Support extensible model to register custom external faker service

    Support the ability to create a new faker service externally and provide support from within Faker class to use the external faker data.

    The alternative is to make a PR to this code repo, however, what if the data in the faker service is specific to an industry that may not apply to everyone.

    Maybe consider an interface and service loader approach in which subtypes of the interface are registered with the Faker service using the Java ServiceLoader pattern.

    opened by dnicholas2001 15
  • Introduce a way to specify the format of the generated phone numbers

    Introduce a way to specify the format of the generated phone numbers

    To illustrate what I mean:

    Somehow give the ability to choose a format of a phone number, for example among these:

    (###) ###-####
    ### ### ####
    ###-###-####
    ##########
    +#-###-###-####
    +# (###) ###-####
    
    opened by panilya 14
  • Proposal to use ThreadLocalRandom instead of Random

    Proposal to use ThreadLocalRandom instead of Random

    Hi guys, do you think does it worth to consider using ThreadLocalRandom instead of Random class? Does it worth to perform some benchmarks regarding this and check performance results?

    Problem

    ThreadLocalRandom theoretically should work faster than Random class.

    Solution

    Use ThreadLocalRandom instead of Random in RandomService class.

    opened by NarekDW 12
  • Apply eclipse code style

    Apply eclipse code style

    This is kind another attempt to apply styling. Finally I refused using google-format-plugin since it's not very configurable... From that point of view eclipse-formatter gives much more freedom (could be applied in IntellijIdea as well) Full configuration could be found at src/main/config/eclipse-java-formatter.xml

    At the same time spotless gives autoformatting based on provided configurations

    so just run mvn spotless:apply or ./mvnw spotless:apply (the PR is mostly a result of this command)

    Current configuration does not touch javadoc => should not be issues like mentioned at https://github.com/datafaker-net/datafaker/pull/220#issuecomment-1159690778

    it also should fix https://github.com/datafaker-net/datafaker/issues/469 // cc @NarekDW @bodiam

    opened by snuyanzin 12
  • Error involving `Csv.Column.of()`

    Error involving `Csv.Column.of()`

    I trying to generate fake data in csv format. The way I do it, is by having enum that looks like this:

    public enum Provider {
            FIRST_NAME(() -> "first_name", faker -> faker.name().firstName());
    
            private final Supplier<String> header;
            private final Function<Faker, String> provider;
    
            Provider(Supplier<String> header, Function<Faker, String> provider) {
                this.header = header;
                this.provider = provider;
            }
        }
    

    The problem in this piece of code:

                result.add(Csv.Column.of(() -> provider.getHeader(), faker -> provider.getProvider().apply(this.faker)));
    

    First argument of Csv.Column.of() returns error which says: Required type: Column Provided: CollectionColumn<T> Supplier<String> is not compatible with String

    Stack trace:

    java: no suitable method found for of(()->provid[...]der(),(faker)->p[...]aker))
        method net.datafaker.fileformats.Csv.CollectionColumn.<T>of(java.util.function.Supplier<java.lang.String>,java.util.function.Function<T,java.lang.String>) is not applicable
          (cannot infer type-variable(s) T
            (argument mismatch; bad return type in lambda expression
              java.util.function.Supplier<java.lang.String> cannot be converted to java.lang.String))
        method net.datafaker.fileformats.Csv.Column.of(java.lang.String,java.util.function.Supplier<java.lang.String>) is not applicable
          (argument mismatch; java.lang.String is not a functional interface)
        method net.datafaker.fileformats.Csv.Column.of(java.util.function.Supplier<java.lang.String>,java.util.function.Supplier<java.lang.String>) is not applicable
          (argument mismatch; bad return type in lambda expression
              java.util.function.Supplier<java.lang.String> cannot be converted to java.lang.String)
    
    

    Maybe I'm doing it wrong and there is another way to implement this.

    opened by panilya 12
  • Non-standard language tags for

    Non-standard language tags for "Belarusian" and "English (Pakistan)" locales

    Faker uses tags by and en-PAK for these locales. But the standard ones are be (or be-BY) and en-PK, see the standard locales list. These non-standard tags are usable with Faker but Java does not recognize them:

    import java.util.Locale;
    
    public class Test {
    
        public static void main(String[] args) {
            System.out.println(getLocaleDisplayName("by"));     // by
            System.out.println(getLocaleDisplayName("be-BY"));  // Belarusian (Belarus)
            System.out.println(getLocaleDisplayName("be"));     // Belarusian
    
            System.out.println(getLocaleDisplayName("en-PAK")); // pak
            System.out.println(getLocaleDisplayName("en-PK"));  // English (Pakistan)
        }
    
        static String getLocaleDisplayName(String languageTag) {
            return Locale.forLanguageTag(languageTag)
                    .getDisplayName(Locale.ENGLISH);
        }
    }
    

    I think there should be added be.yml (or be-BY.yml) and en-PK.yml. The by.yml and en-PAK.yml can be left for backward compatibility.

    opened by alx-mag 1
  • Add java object transformer

    Add java object transformer

    Another transformer which could fill java objects e.g. this will generate a collection of Person objects according to schema

    JavaObjectTransformer jTransformer = new JavaObjectTransformer();
            Schema<Object, ?> schema = Schema.of(
                field("firstName", () -> faker.name().firstName()),
                field("lastName", () -> faker.name().lastName()),
                field("birthDate", () -> faker.date().birthday()),
                field("id", () -> faker.number().positive()));
    
            Collection<Person> persons = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                persons.add(jTransformer.apply(Person.class, schema));
            }
    

    full example is here https://github.com/datafaker-net/datafaker/pull/513/files#diff-b7465230f153bf0f00c1788b28aeb4a239eac7c4438819f5bf6134943b993177R13-R42

    cc @bodiam since you were looking for something like that afair

    opened by snuyanzin 1
Most popular Mocking framework for unit tests written in Java

Most popular mocking framework for Java Current version is 3.x Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any bre

mockito 13.6k Jan 9, 2023
JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.

pact-jvm JVM implementation of the consumer driven contract library pact. From the Ruby Pact website: Define a pact between service consumers and prov

Pact Foundation 962 Dec 31, 2022
Roman Beskrovnyi 248 Dec 21, 2022
A Java architecture test library, to specify and assert architecture rules in plain Java

ArchUnit is a free, simple and extensible library for checking the architecture of your Java code. That is, ArchUnit can check dependencies between pa

TNG Technology Consulting GmbH 2.5k Jan 2, 2023
Never debug a test again: Detailed failure reports and hassle free assertions for Java tests - Power Asserts for Java

Scott Test Reporter for Maven and Gradle Get extremely detailed failure messages for your tests without assertion libraries, additional configuration

Dávid Csákvári 133 Nov 17, 2022
IntelliJ IDEA and JUnit: Writing, Finding, and Running Tests

IntelliJ IDEA and JUnit: Writing, Finding, and Running Tests ?? Webinar https://blog.jetbrains.com/idea/2021/11/live-stream-recording-intellij-idea-an

Christian Stein 11 Jul 23, 2022
Library that allows tests written in Java to follow the BDD style introduced by RSpec and Jasmine.

J8Spec J8Spec is a library that allows tests written in Java to follow the BDD style introduced by RSpec and Jasmine. More details here: j8spec.github

J8Spec 45 Feb 17, 2022
A modern testing and behavioural specification framework for Java 8

Introduction If you're a Java developer and you've seen the fluent, modern specification frameworks available in other programming languages such as s

Richard Warburton 250 Sep 12, 2022
Fluent assertions for Java and Android

What is Truth? Truth makes your test assertions and failure messages more readable. Similar to AssertJ, it natively supports many JDK and Guava types,

Google 2.6k Jan 5, 2023
Java (and original) version of Hamcrest

Java Hamcrest Licensed under BSD License. What is Hamcrest? Hamcrest is a library of matchers, which can be combined in to create flexible expressions

Hamcrest 2k Jan 5, 2023
Playwright is a Java library to automate Chromium, Firefox and WebKit with a single API.

Playwright is a Java library to automate Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.

Microsoft 634 Jan 8, 2023
A BDD-style test runner for Java 8. Inspired by Jasmine, RSpec, and Cucumber.

Spectrum A colorful BDD-style test runner for Java Spectrum is inspired by the behavior-driven testing frameworks Jasmine and RSpec, bringing their ex

Greg Haskins 143 Nov 22, 2022
Advanced Java library for integration testing, mocking, faking, and code coverage

Codebase for JMockit 1.x releases - Documentation - Release notes How to build the project: use JDK 1.8 or newer use Maven 3.6.0 or newer; the followi

The JMockit Testing Toolkit 439 Dec 9, 2022
MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Rub

MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby. MockServer also includes a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding).

Mock-Server 4k Jan 4, 2023
Apache JMeter - An Open Source Java application designed to measure performance and load test applications

An Open Source Java application designed to measure performance and load test applications. By The Apache Software Foundation What Is It? Apache JMete

The Apache Software Foundation 6.7k Jan 1, 2023
ScalaTest is a free, open-source testing toolkit for Scala and Java programmers

ScalaTest is a free, open-source testing toolkit for Scala and Java programmers.

ScalaTest 1.1k Dec 26, 2022
Named and Optional parameters for Java 17

Named Parameters Named and Optional parameters for Java 17 Abstract While working on another project, I found a way to make the Java compiler attribut

Alessandro Autiero 19 Sep 30, 2022
Ready-to-use UI Test Automation Architecture using Java and Selenium WebDriver.

Selenium Test Automation Boilerplate Ready-to-use UI Test Automation Architecture using Java and Selenium WebDriver. Languages and Frameworks The proj

Tahanima Chowdhury 133 Dec 26, 2022
make async-await code style available in java just like csharp and es6

JAsync - the async-await pattern of Java 中文版 JAsync implements Async-Await pattern just like es in Java. It allows developers to write asynchronous co

null 124 Dec 26, 2022