Behavior-Driven Development in Java with JGiven

Jan Schäfer

@JanSchfr

7th Nov 2016

Devoxx Belgium 2016

github.com/spring-projects/spring-petclinic

Typical Test


@Test
public void shouldInsertPetIntoDatabaseAndGenerateId() {
    Owner owner6 = this.clinicService.findOwnerById(6);
    int found = owner6.getPets().size();

    Pet pet = new Pet();
    pet.setName("bowser");
    Collection<PetType> types = this.clinicService.findPetTypes();
    pet.setType(EntityUtils.getById(types, PetType.class, 2));
    pet.setBirthDate(new DateTime());
    owner6.addPet(pet);
    assertThat(owner6.getPets().size()).isEqualTo(found + 1);

    this.clinicService.savePet(pet);
    this.clinicService.saveOwner(owner6);

    owner6 = this.clinicService.findOwnerById(6);
    assertThat(owner6.getPets().size()).isEqualTo(found + 1);
    // checks that id has been generated
    assertThat(pet.getId()).isNotNull();
}
  
github.com/spring-projects/spring-petclinic

Issues with Typical Tests

  • Many technical and irrelevant details
  • Point of the test often hard to grasp
  • Code duplication
  • Can only be read by developers
  • Cannot be used as documentation

Behavior-Driven Development

BDD Scenario


  Scenario: Pets can be assigned to pet owners

   Given a pet owner
     And a dog
    When assigning the pet to the pet owner
    Then the pet owner owns an additional pet
 

BDD Frameworks for Java

  • Cucumber: Plain Text + Java
  • JBehave: Plain Text + Java
  • Concordion: HTML + Java
  • Fitness: Wiki + Java
  • Spock: Groovy
  • ScalaTest: Scala
  • Jnario: Xtend
  • Serenity BDD (similar concepts as JGiven)
 

Stack Overflow?

Goals

  • Developer friendly (low maintancence overhead)
  • Readable tests in in Given-When-Then-Form (BDD)
  • Reusability of test code
  • Readable reports for domain experts

Demo

Example Reports

Summary

  • Developer friendly
  • Highly modular and reusable test code
  • Just Java, no further language is needed
  • Easy to integrate into existing test infrastructures
  • Open Source (Apache 2 Licence)
  • Maven and Jenkins plugins
  • Domain experts can read scenario reports
  • Domain experts can not write scenarios
    (But they can write them in any other format and developers can easily translate them to JGiven)

Thank You!

@JanSchfr

jgiven.org

github.com/TNG/JGiven