I have an extension method for testing so I can do this:
var steve = new Zombie();
steve.Mood.ShouldBe("I'm hungry for brains!");
The extension method:
public static void ShouldBe<T>(this T actual, T expected)
{
Assert.That(actual, Is.EqualTo(expected));
}
This shows:
Expected: "I'm hungry for brains!"
But was: "I want to shuffle aimlessly"
Is there any hack I can pull off to get the name of the property "BrainsConsumed" from within my extension method? Bonus points would be the instance variable and type Zombie.
UPDATE:
The new ShouldBe:
public static void ShouldBe<T>(this T actual, T expected)
{
var frame = new StackTrace(true).GetFrame(1);
var fileName = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber() - 1;
var code = File.ReadAllLines(fileName)
.ElementAt(lineNumber)
.Trim().TrimEnd(';');
var codeMessage = new Regex(@"(^.*)(\.\s*ShouldBe\s*\()([^\)]+)\)").Replace(code, @"$1 should be $3");
var actualMessage = actual.ToString();
if (actual is string)
actualMessage = "\"" + actual + "\"";
var message = string.Format(@"{0} but was {1}", codeMessage, actualMessage);
Assert.That(actual, Is.EqualTo(expected), message);
}
and this prints out:
steve.Mood should be "I'm hungry for brains!" but was "I want to shuffle aimlessly"
Thanks everyone, esp. Matt Dotson, this is awesome. BTW don't feed the silky trolls people.