public static void ShouldNotBeNull<T>(this T actualValue)
{
Assert.IsFalse(actualValue == null, "Object is null, and should not be null.") ;
}
I would like to provide a variable name in the error string on my tests. I开发者_运维知识库 have this as an extension method. Is it possible to get the real parameter name of the variable being passed in?
One option I've written up before is using anonymous types. For example, you'd have:
public void Foo(string x, string y, string z) // x and z must not be null
{
new { x, z }.AssertNoNullElements();
}
with a generic AssertNotNull
method which performs some reflection etc once, and caches the property accesses as delegates in order to hit performance as little as possible.
It's not something I'd generally recommend though. It's not refactor-proof, it creates a new object on each call, and it's generally a bit of an abuse of anonymous types. Admittedly if this is only for tests, the performance aspect isn't as bad...
Consider
public static void ShouldNotBeNull<T>(this T actualValue, string variableName)
{
Assert.IsFalse(actualValue == null, variableName + " is null, and should not be null.") ;
}
No, the caller may very well not even have a variable name assigned to the 'this' parameter or any other parameter
精彩评论