使用 NUnit 测试 ASP.NET MVC 应用程序时对 DataContext 的空引用
我有一个 ASP.NET MVC 应用程序,其中添加了一个用于测试的单独项目。我知道在运行单元测试时使用数据库连接的优点和缺点,并且我仍然想使用它。然而,每次我使用 NUnit 工具运行测试时,由于我的数据上下文为空,它们都会失败。我听说有一个用于测试程序集的单独配置文件,但我不确定我是否正确执行了该操作,或者是否完全有效。
I have an ASP.NET MVC application with a separate project added for tests. I know the plusses and minuses of using the connection to the database when running unit tests, and I still want to use it. Yet, every time when I run the tests with the NUnit tool, they all fail due to my Data Context being null. I heard something about having a separate config file for the tests assembly, but i am not sure whether I did it properly, or whether that works at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你应该检查这个这里的讨论,它应该与我也遇到了同样的问题。
我解决问题的方法就是将我的 Web 配置内容复制到测试项目中的应用程序配置,瞧,数据库连接恢复,在 MVC 领域一切都很好。
i think you should check this discussion here, it should be related as i was having the same problem.
and how i solve my problem was just to copy my web config content to the app config inside he test project and voila, database connection restore and all is fine in the land of mvc again.
您如何创建数据上下文?它是如何运用在你的行动中的?通常,它会使用您在设计器中设置类时引用的数据库,以便您获得一个与您用于设计器的内容相关联的上下文,这可以说不是您想要的单元测试,因此您可以将 app.config 文件添加到单元测试项目中,并将连接字符串更改为测试数据库。它通常不会导致空数据上下文。
我怀疑您的单元测试根本没有触及在调用操作方法之前创建数据上下文的代码。但如果没有代码,确实无法判断。
How are you creating your data context? How is it used in your action? Typically, it will use the database referred to when you set up the classes in the designer so you'd get a context connected to what you used for the designer which is, arguably, not what you want for unit tests, thus you add an app.config file to your unit test project and change the connection string to your test database. It doesn't usually result in a null data context.
I suspect that your unit test is simply not touching the code that creates the data context before you invoke the action method. Without code though, it's really impossible to tell.