我正在使用ASP.NET MVC4
,Microsoft.VisualStudio.TestTools.UnitTesting
和Jenkins
。在我的web.config中,我想通过单元测试确保属性debug
设置为false
:
<configuration>
[...]
<system.web>
<compilation debug="false">
[...]
如何使用单元测试确保?
[TestClass]
public class WebConfigTest
{
/// <summary>
/// in Web.config, debug mode must be set to 'false'
/// </summary>
[TestMethod]
public void TestDebugFalse()
{
// Arrange
// Act
// Assert
Assert.AreEqual(?, "false");
}
}
答案 0 :(得分:2)
这样的测试配置可能会给您一种错误的安全感,因为配置可以在部署后更改。这与您进行单元测试的其余代码不同,后者需要重新编译才能使更改生效。
但是,如果您仍希望对此情况进行测试,则您的测试需要手动加载web.config
文件并将其解析为预期值。 (您无法使用ConfigurationManager
,因为您的测试项目使用自己的app.config
而不是您定位的web.config
。)
例如:
using System.Xml.Linq;
using System.Xml.XPath;
[TestClass]
public class WebConfigTest
{
/// <summary>
/// in Web.config, debug mode must be set to 'false'
/// </summary>
[TestMethod]
public void TestDebugFalse()
{
var path = @"Path to web.config";
var config = XDocument.Load(path);
var compilation = config.XPathSelectElement("/configuration/system.web/compilation");
if(compilation != null)
{
var debug = compilation.Attribute("debug");
if(debug != null)
{
Assert.AreEqual("false", debug.Value);
}
}
}
}
编辑:Joe在评论中提到,您可以使用WebConfigurationManager
获取此信息,而无需进行XML解析。例如:
[TestClass]
public class WebConfigTest
{
/// <summary>
/// in Web.config, debug mode must be set to 'false'
/// </summary>
[TestMethod]
public void TestDebugFalse()
{
var path = @"Path to web.config";
var webConfig = new System.IO.FileInfo(path);
var virtualDirectoryMapping = new System.Web.Configuration.VirtualDirectoryMapping(webConfig.DirectoryName, true, webConfig.Name);
var fileMap = new System.Web.Configuration.WebConfigurationFileMap();
fileMap.VirtualDirectories.Add("/", virtualDirectoryMapping);
var configuration = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(fileMap, "/");
var compilation = configuration.GetSection("system.web/compilation") as System.Web.Configuration.CompilationSection;
if(compilation != null)
{
Assert.AreEqual(false, compilation.Debug);
}
}
}