Compare objects in which some details have different formats

What is the best way to compare all the properties of two objects in which some of them have different formats (for example, DateTime in one and DateTime.ToString() with a custom format in the other)?

I was able to do this using 2 statements:

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

I would think of the following, but this will not compile, because EqualTo<T>() not valid.

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

:

 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(); 
+4
source share
1 answer

The first example is usually the best way. However, if you switch to o1 and o2, this can work in one call. Fluent Assertions will attempt to convert (using Convert.ChangeType) the actual value of the property to the expected value of the property with the same name. In your specific example, it will try to convert DateTime in Dto1 to a string in Dto2 before comparing the values. But since the string representation of DateTime depends on the culture of the stream, this will not give you predictable results. However, if you switch to o1 and o2, I won’t be surprised if Convert.ChangeType successfully converts your short datetime back into a DateTIme.

As a side note, my DTOs usually just pass the DateTime to the caller without converting the strings. I believe that the actual representation of DateTime is solely the responsibility of the UI.

NTN

Dennis

+2
source

Source: https://habr.com/ru/post/1393984/


All Articles