Otu*_*uyh 115 c# unit-testing moq
我陷入了这个代码,我不知道如何模拟:
ConfigurationManager.AppSettings["User"];
Run Code Online (Sandbox Code Playgroud)
我必须模拟ConfigurationManager,但我没有线索,我正在使用Moq.
有人可以给我一个提示吗?谢谢!
Los*_*nos 155
我正在使用AspnetMvc4.刚才我写道
ConfigurationManager.AppSettings["mykey"] = "myvalue";
Run Code Online (Sandbox Code Playgroud)
在我的测试方法中,它工作得很好.
说明:测试方法在上下文中运行,应用程序设置取自,通常为web.config
或myapp.config
.ConfigurationsManager
可以到达这个应用程序 - 全局对象并操纵它.
虽然:如果你有一个并行运行测试的测试运行器,这不是一个好主意.
Jos*_*eld 102
我相信一种标准方法是使用外观模式来包装配置管理器,然后你可以控制松散耦合.
所以你将包装ConfigurationManager.就像是:
public class Configuration: IConfiguration
{
public User
{
get{
return ConfigurationManager.AppSettings["User"];
}
}
}
Run Code Online (Sandbox Code Playgroud)
(您可以从配置类中提取接口,然后在代码中的任何位置使用该接口)然后您只需模拟IConfiguration.您可以通过几种不同的方式实现外观.上面我选择仅包装各个属性.您还可以获得使用强类型信息而不是弱类型哈希数组的附带好处.
Iri*_*dio 21
也许不是你需要完成的,但是你考虑过在你的测试项目中使用app.config吗?因此,ConfigurationManager将获取您在app.config中放置的值,而您无需模拟任何内容.这个解决方案适合我的需求,因为我从不需要测试"变量"配置文件.
Zor*_*ayr 14
您可以使用填充程序修改AppSettings
为自定义NameValueCollection
对象.以下是如何实现此目的的示例:
[TestMethod]
public void TestSomething()
{
using(ShimsContext.Create()) {
const string key = "key";
const string value = "value";
ShimConfigurationManager.AppSettingsGet = () =>
{
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add(key, value);
return nameValueCollection;
};
///
// Test code here.
///
// Validation code goes here.
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在使用Microsoft Fakes隔离测试代码时阅读有关垫片和假货的更多信息.希望这可以帮助.
你考虑过抄袭而不是嘲笑吗?该AppSettings
物业是NameValueCollection
:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// Arrange
var settings = new NameValueCollection {{"User", "Otuyh"}};
var classUnderTest = new ClassUnderTest(settings);
// Act
classUnderTest.MethodUnderTest();
// Assert something...
}
}
public class ClassUnderTest
{
private readonly NameValueCollection _settings;
public ClassUnderTest(NameValueCollection settings)
{
_settings = settings;
}
public void MethodUnderTest()
{
// get the User from Settings
string user = _settings["User"];
// log
Trace.TraceInformation("User = \"{0}\"", user);
// do something else...
}
}
Run Code Online (Sandbox Code Playgroud)
优点是实现更简单,并且在您确实需要之前不依赖于System.Configuration.