c# - 从 app.config 文件的 web.config 部分获取值?

标签 c# .net asp.net web-config app-config

我正在尝试对最终将出现在 web.config 文件中的值进行单元测试。在我的测试项目中,我创建了一个带有 web.config 部分的 app.config 文件来保存设置。在正常情况下,我会调用 System.Configuration.ConfigurationSettings.AppSettings,但在这种情况下,它不起作用。我看到了this question ,这非常相似,但没有解决如何从配置文件中获取 NameValueCollection 的问题。这是配置文件的示例:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
      <membership defaultProvider="CustomMembershipProvider">
        <providers>
          <clear/>
          <add
            name="CustomMembershipProvider"
            applicationName="SettlementInfo"
            enablePasswordRetrieval="false"
            enablePasswordReset="false"
            requiresQuestionAndAnswer="true"
            writeExceptionsToEventLog="true" />
        </providers>
      </membership>
    </system.web>    

</configuration>

有没有人处理过这个问题?

最佳答案

我想我在这里很困惑;看起来您正在尝试测试 ASP.NET 是否正确使用了您的自定义成员资格提供程序。正确的?

如果是这样,我 99.999% 确定您不能使用 MS 框架对其进行单元测试;您必须通过将其部署到网络服务器(或在 VS 中运行 Cassini)并在您的登录页面中输入用户名/密码来对其进行集成测试。

现在,我可能误解了您的请求。如果是这样,请告诉我,我会相应地编辑我的答案。

编辑:

For right now, I'm really just trying to test the NameValue pairs coming out of the config file, to make sure that if the values aren't present, my defaults are being applied. In other words, I want to try to pull applicationName, and verify that it equals "SettlementInfo", and so on. After that, I will be using integration testing to ensure that ASP.NET is using the custom framework in place of the default one. Does that make sense?

我需要的不仅仅是评论,所以我正在编辑。如果我没看错,你是想对你的程序进行单元测试以确保它正确处理配置,是吗?这意味着您要确保您的代码获取正确的 AppSettings 键并处理其中的空值,对吗?

如果是这样,那你就走运了;您根本不需要 app.config 或 web.config,您可以将所需的值设置为测试设置的一部分。

例如:

[TestMethod]
public void Test_Configuration_Used_Correctly()
{
    ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
    MyClass testObject = new MyClass();
    testObject.ConfigurationHandler();
    Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigValue");
}

[TestMethod]
public void Test_Configuration_Defaults_Used_Correctly()
{
    // you don't need to set AppSettings for a non-existent value...
    // ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";

    MyClass testObject = new MyClass();
    testObject.ConfigurationHandler();
    Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigDefaultValue");
}

关于c# - 从 app.config 文件的 web.config 部分获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/612415/

相关文章:

c# - 应用程序不允许 Windows Phone 8 Facebook 登录给定 URL

c# - 如何在母版页的第一个页面加载中只调用一次方法

c# - 是否有当前等效于停产的 "SQL Server English Query"

c# - 是否应该使用 Reflection.Emit 将属性作为方法发出?

jquery - 从不同域加载页面的最快方法

c# - 如何在 wpf 的用户控件中使用命令绑定(bind)?

mysql - ASPNet 下拉列表从 0 到可用数量

c# - RemoveByPattern 方法不可用

asp.net - 我可以包装一个长文件名吗?

c# - 返回 json 的 <T> 字符串