mercredi 22 juin 2016

How to test if the object is created correctly while keeping the class under test in isolation?

It is often told that writing unit tests one must test only a single class and mock all the collaborators. I am trying to learn TDD to make my code design better and now I am stuck with a situation where this rule should be broken. Or shouldn't it?

An example: class under test has a method that gets a Person, creates an Employee based on the Person and returns the Employee.

public class EmployeeManager {

    private DataMiner dataMiner;

    public Employee getCoolestEmployee() {
        Person dankestPerson = dataMiner.getDankestPerson();
        Employee employee = new Employee();
        employee.setName(dankestPerson.getName() + "bug in my code");
        return employee;
    }

    ...
}

Should Employee be considered a collaborator? If not, why not? If yes, how do I properly test that 'Employee' is created correctly?

Here is the test I have in mind (using JUnit and Mockito):

@Test
public void coolestEmployeeShouldHaveDankestPersonsName() {
    when(dataMinerMock.getDankestPerson()).thenReturn(dankPersonMock);
    when(dankPersonMock.getName()).thenReturn("John Doe");

    Employee coolestEmployee = employeeManager.getCoolestEmployee();
    assertEquals("John Doe", coolestEmployee.getName());
}

As you see, I have to use getName() method of a class that is not under Test.

One possible solution that comes to mind is to extract the task of transforming Persons into Employees to a new method of Employee class, something like

public Employee createFromPerson(Person person);

Am I overthinking the problem? What is the correct way?

Aucun commentaire:

Enregistrer un commentaire