Is it possible to check that a simple expression will always return true?
And I mean this in the easiest way. Say you have a function with the following signature:
public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
// ...
}
Usually it will create a more complex expression of some sort, but if the value
is null
the method should return a constant, always true exp开发者_如何学编程ression. In other words:
public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
if(value == null)
return x => true;
// ...
}
Is this something I can create a unit test for? That when I send in null
as the value, I do get back a constant true expression?
It would be easy enough to test for exactly that expression (the body will be a ConstantExpression
with value true
). But in the general case? No - too complex.
static bool IsConstantTrue(LambdaExpression lambda)
{
return lambda.Body.NodeType == ExpressionType.Constant
&& true.Equals(((ConstantExpression)lambda.Body).Value);
}
with
Expression<Func<SomeType, bool>> exp = x => true; // or some method that
// returns a lambda expression
Assert.IsTrue(IsConstantTrue(exp));
There's no way to do so that I know of. However, if you're willing to refactor a bit:
class Sample<T>
{
public static Func<T, bool> Identity = x => true;
public static Func<T, bool> CreateExpression(string value)
{
if(value == "foo")
return Identity;
return x => value.Length % 2 == 0;
}
}
class Test
{
public void DoTest()
{
Debug.Assert(Sample<string>.CreateExpression("foo") == Sample<string>.Identity);
}
}
What do you mean be "simple" here? It's kind of a woolly term...
In general, the only thing we can seay is that this is yet another manifestation of the halting problem. Consider, how can you you determine the result of a function until all possible parameters, unless you actually run it under all possible parameters? Apart from being practically infeasible, you can't even guarantee a result because of the nature of the halting problem (you don't know the method will even terminate, or what path it may take in the indefinite future).
精彩评论