NUnit 未获取数据库连接字符串 [英] NUnit not picking up the database connection string

查看:54
本文介绍了NUnit 未获取数据库连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目(SLR)和一个 Nunit 测试项目(SLR.Tests)

I have a project(SLR) and an Nunit test project(SLR.Tests)

与数据库交互的方法的每个测试都失败了

Every test of a method that interacts with the database fails with an

对象未设置为对象的实例"

"object not set to an instance of an object"

异常就行

using (SqlConnection con = 
new SqlConnection(ConfigurationManager.ConnectionStrings["isvConnectionString"].ToString()))

将连接字符串硬编码到新语句中按预期工作,并且在运行SLR项目的过程中调用该方法不会抛出任何异常.

Hard coding the connection string into the new statement works as expected, and calling the method in course of running the SLR project does not throw any exceptions.

因此看起来 NUnit 没有选择配置文件

Therefore it appears that NUnit isn't picking up the config file

我已经检查过 SLR 的 Bin 文件夹.Tests 文件夹包含 SLR.DLLSLR.DLL.Config 并且配置文件与 SLR 中的 web.config 文件相同项目.

I've checked that the Bin folder of the SLR. Tests folder contains SLR.DLL and SLR.DLL.Config and that the config file is the same as the web.config file in the SLR project.

Test 项目同时安装了 NUnit(V3.10.1) 和 NUit3TestAdapter(V3.10.0).

The Test project has both NUnit(V3.10.1) and NUit3TestAdapter(V3.10.0) installed.

对这里发生的事情有什么想法吗?

Any thoughts on what's going on here?

推荐答案

测试项目需要 app.cofig 具有与被测试项目类似的设置.

The test project needs app.cofig with similar settings present as in the project being tested.

测试项目在单独的应用域中运行,因此它们需要自己的配置文件.

Test projects run in a separate app domain so they need their own config file.

ConfigurationManager 读取当前正在运行的应用程序域的配置文件,因此从正在测试的项目中复制所需的配置设置,以允许按预期执行测试.

The ConfigurationManager reads the config file of the current app domain being run so copy the desired configuration settings over from the project being tested to allow the tests to be exercised as expected.

这个问题还暴露了您的代码如何与直接使用 ConfigurationManager 的实现问题紧密耦合,您应该考虑抽象配置访问,以便可以模拟/替换它们以允许单元测试单独完成.

This issue also exposes how your code is tightly coupled to implementation concerns in terms of using ConfigurationManager directly, and you should consider abstracting configuration access so that they can be mocked/replaced to allow unit tests to be done in isolation.

public interface IConfiguration {
    string AppSetting[string key] { get; }
    string ConnectionStrings[string name] { get; } 
}

这篇关于NUnit 未获取数据库连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆