HO到单元测试静态类,该类具有读取不同配置值的方法
public static class Settings
{
public static bool IsFlagEnabled()
{
bool isFlag;
bool.TryParse(ConfigurationManager.AppSettings["isFlag"], out isFlag);
return isFlag;
}
}
//单元测试
[Fact]
public void isFlagEnabled()
{
// act
var isFlagEnabled = Settings.IsFlagEnabled();
// assert
Assert.True(isFlagEnabled);
}
//单元测试始终返回false for配置值
public static class Settings
{
public static bool IsFlagEnabled()
{
bool isFlag;
bool.TryParse(ConfigurationManager.AppSettings["isFlag"], out isFlag);
return isFlag;
}
}
// Unit Test
[Fact]
public void isFlagEnabled()
{
// act
var isFlagEnabled = Settings.IsFlagEnabled();
// assert
Assert.True(isFlagEnabled);
}
//The unit tests always returns false for the config value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的单位测试实际试图测试什么?
在第一种情况下,您可以直接测试
bool.tryparse
,或进行扩展,bool asbool(此名称valuecollection self,string键)...
提供更方便的访问 +解析。第二种情况可能不是很有意义,因为该功能是由框架提供的,但是应该可以设置构建,以便为单位测试提供配置文件,并带有一些测试数据。
在第三种情况下,您需要一个实际的配置文件来加载,因此测试可能会更麻烦,但是如果您可以检测到某人编写“ TROE”而不是“ True”,也可能会提供更多的价值。
请记住,单位测试应提供值。根据我的经验,对非常简单的方法或涉及大量依赖的方法的单位测试往往比依赖关系的高度复杂方法提供的价值较低。我建议您反对教条规则,例如“所有方法必须进行单位测试”。
What is your unit test actually trying to test?
In the first case you could just test
bool.TryParse
directly, or make an extension,bool AsBool(this NameValueCollection self, string key) ...
to provide a more convenient access + parsing.The second case would probably not be very meaningful since the functionality is provided by the framework, but it should be possible to setup the build to provide the unit test with a configuration file with some test data.
In the third case you need an actual config file to load, so it will probably be more cumbersome to test, but might also give more value if you can detect that someone wrote "troe" instead of "true".
Keep in mind that unit tests should provide value. In my experience unit testing of very simple methods, or methods involving lots of dependencies, tend to provide lower value than highly complex methods with few dependencies. I would recommend against dogmatic rules like "all methods must be unit tested".