Test driven development

Report a typo

Imagine that you got a task to fix an implementation of a Person class to make it pass the following unit tests written according to business logic requirements:

@Test
void testPersonCreationValidArgs() {
    String name = "Jane Doe";
    int age = Person.MIN_AGE + 23;
    Person person = new Person(name, age);

    assertEquals(name, person.getName());
    assertEquals(age, person.getAge());
}

@Test
void testPersonCreationNegativeAge() {
    String name = "Jane Doe";
    int age = Person.MIN_AGE - 1;
    Person person = new Person(name, age);

    assertEquals(Person.MIN_AGE, person.getAge());
}

@Test
void testPersonCreationAgeOverUpperLimit() {
    String name = "Jane Doe";
    int age = Person.MAX_AGE + 1;
    Person person = new Person(name, age);

    assertEquals(Person.MAX_AGE, person.getAge());
}

@Test
void testPersonCreationNameNull() {
    String name = null;
    int age = Person.MIN_AGE + 1;
    Person person = new Person(name, age);

    assertNotNull(person.getName());
    assertEquals(Person.DEFAULT_NAME, person.getName());
}

@Test
void testPersonCreationNameBlank() {
    String name = "\t";
    int age = Person.MIN_AGE + 1;
    Person person = new Person(name, age);

    assertEquals(Person.DEFAULT_NAME, person.getName());
}

@Test
void testPersonCreationNameEmpty() {
    String name = "";
    int age = Person.MIN_AGE + 1;
    Person person = new Person(name, age);

    assertEquals(Person.DEFAULT_NAME, person.getName());
}

The Person class has a constructor that accepts two arguments, String name and int age, and should set the name and the age fields of the object according to the criteria set out in the unit tests.

Write a program in Java 17
class Person {
// Do not change these fields
public static final String DEFAULT_NAME = "Unknown";
public static final int MAX_AGE = 130;
public static final int MIN_AGE = 0;
private String name;
private int age;

// Fix the constructor to make its code pass the unit tests
Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}
}
___

Create a free account to access the full topic