jeudi 28 juillet 2016

How to write unit test with methods that contains another methods?

Well, I have a method that use another method. I have the tests of the secondary method, and now I want to write the unit tests for the main method.

I think that I have to write tests without seeing the code of the method to tests, I mean, I don't have desing the tests thinking in the implementation, so following this, in the tests of the main method I have to tests functionality of the secondary method and the functionality of the main method.

For example, I have two garages with cars. In the garaga a have cars and the number of cars that I have. So I wnat to be able to add a new car to a garaga, remove a car and transfer a car from a garage to another. So I have this methods:

  • One method to add the car to a garage, that have to related the car with the garaga and udpdate the number of the cars. This is when I have a new car.
  • One method to remove a car from a garage, that unrelated the car with the garage and update the number of the cars. This is when I don't have the car anymore, for example because I sold it.
  • On method to transfer the car, that remove the car from the first garage and add the car to the new garage. So this method calls the add method and the remove method.

The code for the transfer method would be something like that:

public void transferCar(garage1, garage2, car)
{
    removeCar(garage1, car);
    addCar(garage2, car);
}

If I test removeCar and addCar and I am sure that they work as expected, to test transfer, I have to test all the cases for addCar and also all the cases for removeCar? Because if I don't know the implementation of transferCar, I don't know if this method use removeCar and addCar, so I don't know if the method works as expected.

In another words, when I test transferCar, the test has to cover 100% of the code of the removeCar, 100% of the code of addCar and 100% of the code of the transferCar method or to ensure that I call the method removeCar once and addCar in the transferCar and it works as expected it is enough, although the removecar and addCar is not covered 100%?

Because if I have to test all the cases of removeCar and addCar, I am doing the same tests twice. So my I have refactored code because removeCar and addCar I use it in many places, but in my test code I have the same tests many times.

This is a very single example, but if I have a method that use few methods and this other methods use antohers, and the main mathod should coverages all the code of all the methods, it would be a very long tests, and a lot of work.

In sumary, when I test a method, I have cover 100% of the code of this method and the 100% of the code of the methods that are used by this method or just to ensure that the main method works as expected and call once each secondary method?

Thanks.

Aucun commentaire:

Enregistrer un commentaire