场景:
我有一个带有方法的类,其中一个方法返回一个表达式树。 我该如何模拟该方法。
代码:
public Expression<Func<SpecFinderDataModel, bool>> BuildDynamicWhereClause(DataTableAjaxPostModel model)
{
var predicate = PredicateBuilder.New<SpecFinderDataModel>(true);
if (_stringValidator.IsValid(model.search.value))
predicate = _basicSearchService.DoSearch(model.search.value, predicate);
var searchData = model.columns.Where(x => x.search.value != null);
predicate = _advancedSearchService.DoSearch(model.isActive, searchData, predicate);
return predicate;
}
此处_advancedSearchService.DoSearch()
会返回Expression<Func<SpecFinderDataModel, bool>>
。我写了下面的测试
测试:
[TestMethod]
[TestCategory("BuildDynamicWhereClause")]
public void BuildDynamicWhereClauseTest()
{
DataTableAjaxPostModel searchmodel = new DataTableAjaxPostModel()
{
columns = new List<Column>()
{
new Column() {
data ="Status",
orderable ="true",
searchable ="true",
search = new Search() {
regex = "false",
value ="TestStatus"
}
}
},
search = new Search()
};
IFinderBuildQueryFlow _finderBuildQueryFlow = new FinderBuildQueryFlow(
_mockBasicSearchService.Object, _mockAdvancedSearchService.Object, _mockStringValidator.Object);
var predicate = PredicateBuilder.New<SpecFinderDataModel>(true);
_mockStringValidator.Setup(x => x.IsValid(searchmodel.search.value)).Returns(false);
var searchData = searchmodel.columns.Where(x => x.search.value != null);
_mockAdvancedSearchService.Setup(x => x.DoSearch(searchmodel.isActive, searchData, predicate).Compile()(model)).Returns(true);
var test = _finderBuildQueryFlow.BuildDynamicWhereClause(searchmodel).Compile()(model);
}
之前的一切
_mockAdvancedSearchService.Setup(x => x.DoSearch(searchmodel.isActive, searchData, predicate).Compile()(model)).Returns(true);
工作正常。
但是我不知道如何模拟advancedSearch.DoSearch()
方法。
任何建议都会很有帮助。谢谢
更新#1:
这是执行该行代码时的错误
更新#2:
因此在此谓词将返回为null
。
答案 0 :(得分:1)
如果要模拟对_advancedSearchService.DoSearch()的调用,则必须按以下步骤进行设置:
const arr = [{image_id: "80", imagename: "Image1",firstx: "267", firsty: "403"},
{image_id: "80", imagename: "Image1",firstx: "320", firsty: "470"},
{image_id: "80", imagename: "Image2",firstx: "126", firsty: "237"}
];
console.log(arr.map(Object.values));
鉴于Expression<Func<SpecFinderDataModel, bool>> query = model => true;
_mockAdvancedSearchService.Setup(x => x.DoSearch(searchmodel.isActive, It.IsAny<IEnumerable<Column>>(), It.IsAny<Expression<Func<SpecFinderDataModel, bool>>>())).Returns(query);
参数是在方法本身中创建的,您将需要为其接受任何值。
鉴于searchdata
参数是在方法本身中创建的,您将需要为其接受任何值。