例如,我有SomeClass
类实现ISomeInterface
接口,其中包含两个属性Prop1
和Prop2
(Prop1
没有setter !!!和{{ 1}}取决于Prop2
):
Prop1
我需要为这个类编写单元测试。我建议他们应该看起来像:
public class SomeClass : ISomeInterface
{
private readonly NameValueCollection settings = ConfigurationManager.AppSettings;
private readonly string p1;
private string p2;
public string Prop1 { get { return settings["SomeSetting"]; } }
public string Prop2
{
get
{
switch(Prop1)
{
case "setting1": return "one";
case "setting2": return "two";
case "setting3": return "three";
default: return "one";
}
}
set { p2 = value; }
}
}
所以我的问题是:[TestMethod]
public void Prop2ShouldReturnOneValueIfSomeSettingEqualsSetting1()
{
var someClass = new SomeClass();
Assert.Areequals(someClass.Prop2, "one");
}
[TestMethod]
public void Prop2ShouldReturnTwoValueIfSomeSettingEqualsSetting2()
{
var someClass = new SomeClass();
Assert.Areequals(someClass.Prop2, "two");
}
我无法将字段所需的值设置为字段,因为它们是私有的。我应该模仿How can I force Prop1 return setting1, setting2 etc. if it has no setter?
还是ISomeInterface
???如果是这样,如果它没有接口,我该如何模拟ConfigurationManager
?我应该直接模拟ConfigurationManager
类???会不会???另外我不明白我怎么能模仿ConfigurationManager
。我需要测试ISomeInterface
,这取决于prop2
。如果我输入:
prop1
它不会改变任何内容,因为[TestMethod]
public void Prop2ShouldReturnTwoValueIfSomeSettingEqualsSetting2()
{
var moqSettings = new Mock<ISomeInterface>();
moqSettings.Setup(p => p.Prop1).Returns("setting2");
...
}
将是moqSettings.Object.Prop2
。而且,我不确定,但我认为这样做是错误的)))null
P.S。对于模拟,我使用So how can I test all cases in prop2???
。
P.P.S.对不起我的英文)))我希望我能清楚地解释我需要什么...
答案 0 :(得分:1)
我认为你的课有几个职责 - 阅读配置,并根据配置设置生成一些值。如果您拆分这些职责,那么您可以模拟您的应用程序设置。创建一些类似ISomeConfiguration
public interface ISomeConfiguration
{
string SomeSetting { get; }
}
以这种方式实施:
public class MyConfiguration : ISomeConfiguration
{
readonly NameValueCollection settings = ConfigurationManager.AppSettings;
public string SomeSettings
{
get { return settings["SomeSetting"]; }
}
}
并将此界面注入您的SomeClass
:
public class SomeClass : ISomeInterface
{
private readonly string p1;
private string p2;
private ISomeConfiguration config;
public SomeClass(ISomeConfiguration config)
{
this.config = config;
}
public string Prop1 { get { return config.SomeSetting; } }
public string Prop2
{
get
{
switch(Prop1)
{
case "setting1": return "one";
case "setting2": return "two";
case "setting3": return "three";
default: return "one";
}
}
set { p2 = value; }
}
}
现在您可以毫无问题地模拟配置:
[TestMethod]
public void Prop2ShouldReturnTwoValueIfSomeSettingEqualsSetting2()
{
var moqConfig = new Mock<ISomeConfiguration>();
moqConfig.Setup(p => p.SomeSetting).Returns("setting2");
var sut = new SomeClass(moqConfig.Object);
Assert.That(sut.Prop2, Is.EqualTo("two"));
}