Skip to content

Commit 4e64fff

Browse files
knoctejagregory
authored andcommitted
[Property testing]: prevent throwing a very confusing error like "For property 'Foo' expected 'Bar' of type 'Bar' but got 'Bar' of type 'Bar'"
1 parent 47724b7 commit 4e64fff

File tree

1 file changed

+61
-7
lines changed

1 file changed

+61
-7
lines changed

src/FluentNHibernate/Testing/Values/Property.cs

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,17 +79,71 @@ public override void CheckValue(object target)
7979

8080
if (!areEqual)
8181
{
82-
string message =
82+
throw new ApplicationException(GetInequalityComparisonMessage(actual));
83+
}
84+
}
85+
86+
private string GetInequalityComparisonMessage(object actual)
87+
{
88+
string message;
89+
90+
string actualToPrint = actual.ToString();
91+
string actualTypeToPrint = PropertyAccessor.PropertyType.FullName;
92+
93+
string valueToPrint = Value != null ? Value.ToString() : "(null)";
94+
string valueTypeToPrint = Value != null ? Value.GetType().FullName : "(null)";
95+
96+
if (actualToPrint != valueToPrint && actualTypeToPrint != valueTypeToPrint)
97+
{
98+
message =
8399
String.Format(
84100
"For property '{0}' expected '{1}' of type '{2}' but got '{3}' of type '{4}'",
85101
PropertyAccessor.Name,
86-
(Value != null ? Value.ToString() : "(null)"),
87-
(Value != null ? Value.GetType().FullName : "(null)"),
88-
actual,
89-
PropertyAccessor.PropertyType.FullName);
90-
91-
throw new ApplicationException(message);
102+
valueToPrint,
103+
valueTypeToPrint,
104+
actualToPrint,
105+
actualTypeToPrint);
92106
}
107+
else if (actualToPrint != valueToPrint)
108+
{
109+
message =
110+
String.Format(
111+
"For property '{0}' of type '{1}' expected '{2}' but got '{3}'",
112+
PropertyAccessor.Name,
113+
actualTypeToPrint,
114+
valueToPrint,
115+
actualToPrint);
116+
}
117+
else if (actualTypeToPrint != valueTypeToPrint)
118+
{
119+
message =
120+
String.Format(
121+
"For property '{0}' expected type '{1}' but got '{2}'",
122+
PropertyAccessor.Name,
123+
valueTypeToPrint,
124+
actualTypeToPrint);
125+
}
126+
else if (actualTypeToPrint != actualToPrint)
127+
{
128+
message =
129+
String.Format(
130+
"For property '{0}' expected same element, but got different element with the same value '{1}' of type '{2}'."
131+
+ Environment.NewLine + "Tip: use a CustomEqualityComparer when creating the PersistenceSpecification object.",
132+
PropertyAccessor.Name,
133+
actualToPrint,
134+
actualTypeToPrint);
135+
}
136+
else
137+
{
138+
message =
139+
String.Format(
140+
"For property '{0}' expected same element, but got different element of type '{1}'."
141+
+ Environment.NewLine + "Tip: override ToString() on the type to find out the difference.",
142+
PropertyAccessor.Name,
143+
actualTypeToPrint);
144+
}
145+
146+
return message;
93147
}
94148
}
95149
}

0 commit comments

Comments
 (0)