我对 TDD、ASP.NET MVC 和 LinqToSql 非常陌生。
我正在尝试为我的存储库编写测试,该存储库使用 LinqToSql 从存储过程获取数据。
这是正在测试的存储库方法:
public int GetResponseCount(int campaignId)
{
var results = (new MyDBDataContext()).GetResponseCountById(campaignId);
foreach (GetResponseCountByIdResult result in results)
{
return (result.ResponseCount != null) ? result.ResponseCount.Value : 0;
}
return 0;
}
这是测试中的代码:
var myDBDataContext = new Mock<MyDBDataContext>();
var result = new Mock<ISingleResult<GetResponseCountByIdResult>>().Object();
myDBDataContext.Setup(x => x.GetResponseCountById(It.IsAny<int>())).Returns(result).Verifiable();
...
...
有 2 个问题:
1) sored 过程返回单个整数结果。但我必须循环遍历 LinqToSql 的响应才能获取该值。这并不理想。有更好的方法吗?
2)测试中的代码无法编译。编译器说 - 不可调用成员 'Moq.Mock>.Object' 不能像方法一样使用。
如何编写测试来验证我的存储库方法调用 LinqToSql 中的正确方法?
非常感谢!
I am very new to TDD, ASP.NET MVC and LinqToSql.
I am trying to write tests for my repository, which gets data from stored procedure using LinqToSql.
This is the repository method being tested:
public int GetResponseCount(int campaignId)
{
var results = (new MyDBDataContext()).GetResponseCountById(campaignId);
foreach (GetResponseCountByIdResult result in results)
{
return (result.ResponseCount != null) ? result.ResponseCount.Value : 0;
}
return 0;
}
This is the code in test:
var myDBDataContext = new Mock<MyDBDataContext>();
var result = new Mock<ISingleResult<GetResponseCountByIdResult>>().Object();
myDBDataContext.Setup(x => x.GetResponseCountById(It.IsAny<int>())).Returns(result).Verifiable();
...
...
There are 2 questions:
1) The sored procedure returns a single integer result. But I am having to loop through the response from LinqToSql to get to the value. Which is not ideal. Is there a better way to do it?
2) The code in test does not compile. The compiler says - Non-invocable member 'Moq.Mock<System.Data.Linq.ISingleResult<GetResponseCountByResult>>.Object' cannot be used like a method.
How can I write test to verify that my repository method calls the right method in LinqToSql?
Many Thanks!
发布评论
评论(1)
我倾向于封装对 DataContext 的访问,以便您可以拦截对它的访问(从而模拟 DC)以进行单元测试。这种方法允许您在需要时调整查询以获得单一结果:
这样,您可以模拟数据上下文,在单元测试中提供您自己的结果,还可以调整查询以从您的查询中获取第一个答案。当您确信只有一个结果时,请按顺序进行排序。
最美好的祝愿,
安德鲁
I'd be inclined to encapsulate access to your DataContext so that you can intercept access to it (and thus mock the DC) for unit testing. this approach allows you to adapt your queries to get the single result when you need to:
That way, you can mock the data context, providing your own results inside of your unit tests, and also adapt the query to get the first answer from your sequence when you are confident that there is only one result.
Best Wishes,
Andrew