使用 Linq to Sql 进行 MVC 单元测试
我有一个控制器正在我的站点中工作,但在单元测试期间失败。它非常简单,依赖于 Linq to Sql 返回 JSON 对象的集合。
测试失败,因为从 MVC 项目外部调用 DataContext 时找不到连接字符串。
我查看了自动生成的代码:
public DC():
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
Web 项目可以在 web.config 中找到“myConnectionString”条目,但测试项目找不到它。我收到的错误消息是:
Test method MyMVCApp.Controllers.HomeControllerTest.IndexShouldReturnIssues threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
我不想从单元测试中传递另一个连接字符串,因为我想测试 web.config 中的连接字符串是否有效。
谢谢, 约翰
I have a controller that is working in my site but failing during unit testing. It is pretty simple and depends on Linq to Sql to return a collection of JSON objects.
The Test fails because the DataContext can't find the connection string when called from outside the MVC project.
I had a look in the auto generated code:
public DC():
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
The web project can find the "myConnectionString" entry in web.config, but the test project can't find it. The error message I got was:
Test method MyMVCApp.Controllers.HomeControllerTest.IndexShouldReturnIssues threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
I don't want to pass another connection string in from my unit tests because I want to test that the connection string in the web.config works.
Thanks,
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将连接字符串添加到单元测试项目中的 app.config 文件中。
FWIW,我实际上并没有在单元测试中使用真正的数据库(尽管我在集成测试中使用)。我写了一篇关于 LINQ- to-SQL 实现,如果您有兴趣,可以在我的博客上进行模拟在更多信息中。
Add the connection string to the app.config file in your unit test project.
FWIW, I don't actually use a real database in my unit tests (although, I do in integration tests). I wrote about a LINQ-to-SQL implementation that allows mocking on my blog awhile back if you are interested in more info.