How do I write a unit test for a Expression tree in C#.
I have this class which needs to be tested. This method returns a Expression tree and also gets one as a parameter.
code:
public ExpressionStarter<SpecFinderDataModel> DoSearch(bool status, string searchValue, ExpressionStarter<SpecFinderDataModel> predicate)
{
var localPredicate = predicate;
if (status == false)
{
var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());
localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.ProductID.ToLower().Contains(srch)));
localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.ISBN13.ToLower().Contains(srch)));
localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.Title.ToLower().Contains(srch)));
}
return localPredicate;
}
Any advice would be helpful. Thanks.
Update #1 I have used LinqKit for ExpressionStarter
This shall be simple, though I will use the Expression<Func<SpecFinderDataModel,bool>>
instead of LinqKit APIs, which is used internally, In the DoSearch
method, you need Expression<Func<SpecFinderDataModel,bool>>
as input, based on the method assuming following as the definition of the type SpecFinderDataModel
public class SpecFinderDataModel
{
public string ProductID {get; set;}
public string ISBN13 {get; set;}
public string Title {get; set;}
}
Now you need to simply test various options, as done in regular unit test, a sample:
// Initial Expression value constant false is the result
Expression<Func<SpecFinderDataModel, bool>> expr = c => false;
// SpecFinderDataModel Object
var sfd = new SpecFinderDataModel
{
ISBN13 = "",
ProductID = "Test A B C",
Title = ""
}
// Call DoSearch and supply the sfd for testing
var result = DoSearch(false,"Test",expr).Compile()(sfd);
// Assert the result in the unit test to understand
Assert.True(result,true);
Like this based on combinations of the DoSearch
parameters and test object sfd
, you can create any number of unit test cases to test your code