mercredi 16 décembre 2015

Can we add methods which is easier for assertion in test and which is only used in tests when TDD?

Here let me take a simple parking boy example.

A parking boy can manage several parking lots, and when a car comes, he will park the car into some parking lot and can also help to un-park the car.

So basically in my mind, there will be a ParkingBoy class like this:

class ParkingBoy {
    public ParkingBoy(List<ParkingLot> parkingLots) {}
    public Ticket park(Car car) {}
    public Car unpark(Ticket ticket) {}
}

But in the practise of TDD, we design the api from the user's perspective, and won't presume what the actual class is and what methods it has. Let the tests drive them.

So I first split the requirement into several small tasks:

1. A parking boy can manage parking lots
2. A parking boy can park a car to any avaiable parking lot, and return a ticket
3. A parking boy can unpark the car for a ticket

When doing the first task, my test is:

class ParkingBoySpec {
    @Test public void should_manage_parking_lots() {
        List<ParkingLot> parkingLots = list(parkingLot1, parkingLot2);
        ParkingBoy boy = new ParkingBoy(parkingLots);
        assertThat(boy.getParkingLots()).containsExactly(pakrkingLot1, parkingLot2);
    }    
}

But my friend has questions about the getParkingLots method.

In his opinion, this method is just used in the assertion of test, and will not be used in anywhere of the implementation, so we should not provide it. And even, we actually don't care the parking lots managed by the boy, what we care is he can park and unpark the car. So we should remove the first task and start from the task 2(park).

My opinion is:

  1. Since we write tests before implementation in TDD, we actually don't know if the getParkingLots will be used in the later implementation.
  2. Although the main purpose of the parking boy is to park and unpark a car, but I want to start from a simple task
  3. The test is the "user" of the code, so when the test thinks if there is a getParkingLots, it's a good reason to provide a getParkingLots in ParkingBoy

How do you think this question?

Aucun commentaire:

Enregistrer un commentaire