Dra*_*ter 12 c# unit-testing mstest moles
我有以下测试:
[TestClass]
public class GeneralTest
{
[TestMethod]
public void VerifyAppDomainHasConfigurationSettings()
{
string value = ConfigurationManager.AppSettings["TestValue"];
Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
}
[TestMethod]
[HostType("Moles")]
public void VerifyAppDomainHasConfigurationSettingsMoles()
{
string value = ConfigurationManager.AppSettings["TestValue"];
Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
}
}
Run Code Online (Sandbox Code Playgroud)
它们之间的唯一区别是[HostType("Moles")].但第一次传球,第二次传球失败.如何从第二次测试中读取App.config?
或者我可以在其他地方添加另一个配置文件?
小智 17
假设您正在尝试访问appSettings中的值,那么只需在测试开始时添加配置即可.就像是:
ConfigurationManager.AppSettings["Key"] = "Value";
Run Code Online (Sandbox Code Playgroud)
然后,当您的测试尝试读取AppSettings"Key"时,将返回"Value".
小智 12
您只需将"App.Config"文件添加到单元测试项目中.它会自动读取.
见http://social.msdn.microsoft.com/Forums/en/pex/thread/9b4b9ec5-582c-41e8-8b9c-1bb9457ba3f6
同时,作为解决方法,您可以尝试将配置设置添加到Microsoft.Moles.VsHost.x86.exe.config
小智 5
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext)
{
System.Configuration.Moles.MConfigurationManager.GetSectionString =
(string configurationName) =>
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly assembly = Assembly.GetExecutingAssembly();
fileMap.ExeConfigFilename = assembly.Location + ".config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
object section = config.GetSection(configurationName);
if (section is DefaultSection)
{
ConfigurationSection configurationSection = (ConfigurationSection) section;
Type sectionType = Type.GetType(configurationSection.SectionInformation.Type);
if (sectionType != null)
{
IConfigurationSectionHandler sectionHandler =
(IConfigurationSectionHandler)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(sectionType.Assembly.FullName, sectionType.FullName);
section =
sectionHandler.Create(
configurationSection.SectionInformation.GetParentSection(),
null,
XElement.Parse(configurationSection.SectionInformation.GetRawXml()).ToXmlNode());
}
}
return section;
};
}
Run Code Online (Sandbox Code Playgroud)