4

What is the best way to compare all properties of two objects where some of them have different formats (e.g. DateTime in one and DateTime.ToString() with custom format in other)?

I was able to do that by using 2 assertions:

o1.ShouldHave().AllPropertiesBut(dto1 => dto1.Date).EqualTo(o2);
o1.Date.Should().Be(DateTime.Parse(o2.Date));

I would think about the following, but that does not compile because EqualTo<T>() is void.

o1.ShouldHave().AllProperties().But(d => d.Date).EqualTo(o2)
.And.Date.Should().Be((DateTime.Parse(o2.Date));

types are:

public class Dto1
{
    public int ID { get { return 1; } }
    public DateTime Date { get { return DateTime.Now.Date; } }
}

public class Dto2
{
    public int ID { get { return 1; } }
    public string Date { get { return DateTime.Now.Date.ToShortDateString(); } }
}

var o1 = new Dto1();
var o2 = new Dto2();
the_joric
  • 11,986
  • 6
  • 36
  • 57

1 Answers1

2

The first example is typically the best way. However, if you would switch o1 and o2, it might work in a single call. Fluent Assertions will try to convert (using Convert.ChangeType) the actual value of a property to the expected value of the property with the same name. In your particular example, it would try to convert the DateTime in Dto1 to a string in Dto2 before comparing the values. But since the string representation of a DateTime is dependent on the culture of the thread, it would not give you predictable results. However, if you would switch o1 and o2, I wouldn't be surprised if Convert.ChangeType would succesfully convert your short datetime back to a DateTIme object.

As a side-note, my DTOs usually just pass the DateTime to the caller without any string conversion. I believe that the actual representation of the DateTime is purely a UI responsibility.

HTH

Dennis

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • Thanks for answer. I understand that DateTime conversion is culture dependent -- that was just an example. Just was wondering why `EqualTo()` does not allow method chaining :) BTW fluentassertions are awesome -- thx for your job. – the_joric Jan 31 '12 at 21:44