Generating Test Data with Faker and friends

During my recent endeavours to build a REST API, I wanted to test the bulk upload feature of the API which required a large set of test data. I was looking for a quick way to create a fake test data set and found an interesting Ruby library called Faker. This a port of Perl’s Data::Faker library.

Faker is a popular choice in Rails community. It is also ported to Java, Python and JavaScript.

Faker provides a number of categories for test data generation. For example Names, Addresses, Pictures, Business & Finance (Credit Card Numbers, IBAN numbers, Swift Codes etc.), Text placeholders and much more.

Let’s say we want to create a list of records on the fly. We want a list of names and contact phone number. In Ruby, all we would have to do is:

First install Faker Gem with:


gem install faker

and create a simple script to generate records:


require 'faker'
require 'json'

landlords = []

100.times do
  landlord = Hash.new
  landlord["name"] = Faker::Name.name
  landlord["contact_number"] = Faker::PhoneNumber.cell_phone
  landlords.push(landlord)
end

puts JSON.pretty_generate(landlords)

This will create records similar to below output. You can copy or store the output and use it seed to database or during the testing


[
  {
    "name": "Ms. Adelia Ortiz",
    "contact_number": "1-443-107-3897"
  },
  {
    "name": "Delores Cassin",
    "contact_number": "868.775.6054"
  },
  {
    "name": "Rose Klocko",
    "contact_number": "759-090-9777"
  },
  {
    "name": "Josiah Langworth I",
    "contact_number": "1-308-497-4606"
  },
  {
    "name": "Kattie Hamill",
    "contact_number": "266-980-1233"
  },
]

We can also use Faker in automated tests. For example here’s Capybara test using a fake user data to test Sign-Up feature:


name = Faker::Name.name
email =  Faker::Internet.email

visit("/signup")

fill_in('account_name', with: name)
fill_in('account_email', with: email)
click_button('Sign Up')

page.has_content?("Dear ${name}")
page.has_content?('Verify Your Email Address')

Here’s JavaScript version of the Ruby script made with Faker.js


var faker = require('faker')

landlords = []
for(i=0; i<100; i++) {
  var user = {
    name: faker.name.findName(),
    email: faker.phone.phoneNumber(),
  };
  landlords.push(user)
}

console.log(landlords);

By default, these libraries generate values which may not be unique. However, you can set options to generate unique values. You can also extend/customise the output.

You can find Java port of the Faker called Java Faker
There is also Python port available at https://github.com/joke2k/faker

Faker and friends are must have power tool for Developers and testers.


Adding Swagger UI support to Spring Boot REST API Project

Recently I was working on a project to build REST API using Spring Boot framework. I was looking for a way to document the service and all the operations supported by the service in an easy way. I used Swagger to document the API with really simple configurations.

Swagger does an awesome job to document your APIs directly from the source code.

The documentation and Swagger’s interactive Web UI helps users to explore the API, try supported operations with different input values and look at the output from the operation or any validations that are configured for the operation. My tester colleagues really liked this API playground.

Let’s explore steps to configure Swagger UI on an existing project.

In order to setup Swagger UI with the project, we will use Springfox library. The Springfox library enables Swagger by scanning the application, at runtime to infer API semantics based on Spring configurations, class structure and various compile time java Annotations. To get started with Springfox, we need to add following dependencies to POM (I’m using Maven for this project):

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.6.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.6.1</version>
  <scope>compile</scope>
</dependency>

Next, we need to configure Docket bean in the Application class which will do the rest of the magic:

@Bean
public Docket simpleDiffServiceApi() {
  return new Docket(DocumentationType.SWAGGER_2)
  .groupName("calculator")
  .apiInfo(apiInfo())
  .select()
  .apis(RequestHandlerSelectors.any())
  .paths(PathSelectors.any())
  .build()
  .pathMapping("/");

}

This will scan the service (in this example the Calculator service request handlers). We also need to pass the API info object which is used to configure API details like Tile, Description, Version, Developer Information etc. See the Springfox docs for more configuration options.

private ApiInfo apiInfo() {
  return new ApiInfoBuilder()
  .title("A simple calculator service")
  .description("A simple calculator REST service made with Spring Boot in Java")
  .contact(new Contact("Unmesh Gundecha", "http://unmesh.me", "upgundecha@gmail.com"))
  .version("1.0")
  .build();
}

Here is the Controller class for the Calculator Service with request handler for the add operation:

@RestController
@RequestMapping("api/v1/")
public class CalculatorController {

  @Autowired
  private Calculator calculatorService;

  @RequestMapping(value = "calculator/add", method = RequestMethod.POST)
  public Result add(@RequestBody Values values) {
  int result = calculatorService.add(values.getFirstNumber(),
  values.getSecondNumber());
  return new Result(result);
  }
}

That’s it. Let’s run this service using

mvn spring-boot:run

This will launch the application. Navigate to http://localhost:8080/swagger-ui.html in a Browser window. This will show the Swagger UI with the service details. In this example it will show the Calculator service with add operation as shown in below screenshot:

swagger1

Let’s open the /api/v1/calculator/add operation. This will show details about this operation as shown in below screenshot:

swagger2

Users can try the add operation or any other operation provided by the service by submitting parameters and using the Try it out! button on the form. Here is add operation in action:

calc_service

Operations can also be further explained using various Swagger Annotations like @ApiOperation, @ApiResponse etc.

You can also define a new API from scratch in Swagger format and generate source code in over dozen different frameworks supported by the Swagger. You can play with Swagger Editor and Swagger Codegen for building new APIs at Swagger Editor