Search code examples
unit-testingfluent-assertions

unit test convert to dto extension method with fluentconversion


if i have a extension method that converts an Person object to a PersonDTO then

  1. should i unit test that the conversion occurs correctly
  2. if so and i use fluentassertions how do i assert that the conversion is correct

my extension method is:

public static PersonDTO ToDto (this Person person)
    {
        if (person == null) return null;
        return new PersonDTO
        {
            FirstName = person.FirstName,
            LastName = person.LastName,
            Dob = person.Dob,
            Identifier= person.Id
        };            
    }

my person object has other properties that are not being mapped.

to get the personDTO object i would therefore do something similar to below:

var newPerson = new Person{ //set properties here };
var personDto = newPerson.ToDto();

Solution

  • First, yes, this code should be tested.

    In order to check that the conversion is correct, you have to build the expected result manually, and then assert that the result of the function is the same:

    var person = new Person{ ... };
    var expectedPersonDto = new PersonDto{ ... };
    person.ToDto().Should().BeEquivalentTo(expectedPersonDto);
    

    See this for more information on comparing object graphs.