我在Massive类上创建了一个Find方法。问题是我刚刚意识到它总是返回true,因为结果永远不会为空。这是我的代码:
public dynamic Find(string email)
{
dynamic result = new ExpandoObject();
dynamic experience = new ExpandoObject();
result.Success = false;
experience = this.Query(@"SELECT we.* FROM WorkExperience we
LEFT JOIN Members m ON m.Id = we.MemberId
WHERE m.Email = @0", email);
if (experience != null)
{
result.Experience = experience;
result.Success = true;
}
return result;
}
在这种情况下,体验永远不会为null所以result.Success总是返回false。如何测试this.Query()是否返回记录?
答案 0 :(得分:1)
我这样做是为了测试我的查询是否带回记录。
控制器:
public ActionResult Index() {
_logger.LogInfo("In home");
//var data = _tricksTable.All(orderBy: "DateCreated");
dynamic viewModel = new ExpandoObject();
var data = _tricksTable.Query("SELECT TOP(10) * FROM Tricks ORDER BY DateCreated DESC");
viewModel.TenTricksNewestFirst = data;
var data2 = _tricksTable.Query("SELECT TOP(10) * FROM Tricks ORDER BY Votes DESC");
viewModel.TenTricksMostPopularFirst = data2;
return View(viewModel);
}
并测试:
[Test]
public void a_user_should_be_able_to_view_10_newest_tricks_in_latest_videos_tab() {
var result = _controller.Index() as ViewResult;
dynamic viewModelExpando = result.ViewData.Model;
var queryFromMassiveDynamic = viewModelExpando.TenTricksNewestFirst;
var i = Enumerable.Count(queryFromMassiveDynamic);
Assert.AreNotEqual(0, i, "TenTricksNewestFirst returned 0 records");
Assert.LessOrEqual(i,10, "Ten Tricks Newest First returned more than 10 tricks");
}
答案 1 :(得分:0)
作为未来求职者的参考,这实际上要简单得多。而不是使用DynamicModel的Query方法,调用Scalar方法并确保您选择a)只有一个值,然后测试结果是否为null或b)匹配计数,您可以从中将结果转换为整数并根据返回的数字进行测试。