我正在尝试为我的项目编写单元测试,但它不会让我使用配置管理器。现在我的项目设置如
ASP.Net应用程序(所有aspx页面)
ProjectCore(所有C#文件 - 模型)
ProjectTest(所有测试)
在我的ProjectCore中,我能够从System.Configuration访问ConfigurationManager对象并将信息传递到项目中。但是,当我运行涉及ConfigurationManager的测试时,我收到错误
System.NullReferenceException: Object reference not set to an instance of an object.
以下是测试的示例
using System.Configuration;
[TestMethod]
public void TestDatabaseExists()
{
//Error when I declare ConfigurationManager
Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
}
在我的其他测试中,ConfigurationManager.ConnectionStrings [“ConnectionString”]。ConnectionString是我将数据适配器的配置字符串设置为,并在测试时返回null错误,但在我实际使用网站时却没有。有什么想法吗?
答案 0 :(得分:25)
这可能是以下几个问题之一:
您没有在app.config中添加连接字符串。
答案 1 :(得分:2)
您正在进行单元测试,在单元测试中,您的注意力应该是尝试测试的特定方法,并且应该删除无关的依赖项。在这种情况下,尝试模拟/鼹鼠(使用Microsoft Mole和Pex)system.configuration
类;这肯定会给出一个解决方案。
我的意思是,一旦你安装MS moles-and-pex - >在您的测试项目解决方案中 - >右键单击系统组件,然后选择create mole。
这会给你一个摩擦版的配置类,而这个版本又会有一个configuration class
的模拟版本 - 使用它你可以绕过你面临的问题。
答案 2 :(得分:1)
它与mstest.exe命令行中的/ noisolation参数有关。 省略/ noisolation参数,它可以工作。
答案 3 :(得分:1)
您还可以使用ExeConfigurationFileMap
:
// Get the machine.config file.
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
// You may want to map to your own exe.config file here.
fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config";
// You can add here LocalUserConfigFilename, MachineConfigFilename and RoamingUserConfigFilename, too
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
答案 4 :(得分:0)
首先,您必须确保在nunit tests项目中有一个app.config文件。
输入连接的详细信息,它将生成一个app.config文件或在其中添加右侧部分:
在您的Test类中,将引用添加到:System.Configuration;。 =>使用System.Configuration;
例如,您可以通过以下方式使用connectionString:
[TestFixture]
public class CommandesDALUnitTest
{
private string _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
[Test]
public void Method_Test()
{
string test = _connectionString;
....
}
}