例如,我有一个SomeClass
类,它实现ISomeInterface
了具有两个属性的接口Prop1
并且Prop2
(Prop1
没有设置器!!!并且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
。而且,我不确定,但我认为这样做是错误的)))So how can I test all cases in prop2???
PS为了模拟我使用Moq
. PPS 对不起我的英语)))我希望我清楚地解释了我需要什么......