无法在单元测试项目中使用ConfigurationManager

wil*_*kao 21 c# sql configuration unit-testing mocking

我正在尝试为我的项目编写单元测试,但它不会让我使用配置管理器.现在我的项目设置像

ASP.Net应用程序(所有aspx页面)

ProjectCore(所有C#文件 - 模型)

ProjectTest(所有测试)

在我的ProjectCore中,我能够从System.Configuration访问ConfigurationManager对象并将信息传递到项目中.但是,当我运行涉及ConfigurationManager的测试时,我收到错误

System.NullReferenceException: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

这是测试的一个例子

using System.Configuration;

[TestMethod]
public void TestDatabaseExists()
{
    //Error when I declare ConfigurationManager
    Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
}
Run Code Online (Sandbox Code Playgroud)

在我的其他测试中,ConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString是我将数据适配器的配置字符串设置为,并在测试时返回null错误,但在我实际使用网站时却没有.有任何想法吗?

Ole*_*Aza 26

这可能是以下几个问题之一:

  1. 您没有将app.config添加到ProjectTest项目中.
  2. 您没有在app.config中添加连接字符串.

  • 哈哈哈oops,我有一个web.config文件而不是app.config.原因是我在ASP.net项目中有web.config,并且由于核心不需要配置文件,它在那里工作,我以为我可以使用相同的那个,但那是noob,感谢提醒 (2认同)