使用 Linq to Sql 进行 MVC 单元测试

发布于 2024-08-06 00:53:11 字数 712 浏览 4 评论 0原文

我有一个控制器正在我的站点中工作,但在单元测试期间失败。它非常简单,依赖于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红衣飘飘貌似仙 2024-08-13 00:53:11

将连接字符串添加到单元测试项目中的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文