For example I have SomeClass class which implements ISomeInterface interface with two properties Prop1 and Prop2 (Prop1 has NO setter!!! and Prop2 depends of 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; }
}
}
I need to write unit tests for this class. I suggest they should look like:
[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");
}
So my question is: How can I force Prop1 return setting1, setting2 etc. if it has no setter? I cannot set the values I need to fields because they are private. Should I mock ISomeInterface or ConfigurationManager??? If so, how can I mock ConfigurationManager if it has no interface??? Should I mock directly ConfigurationManager class??? Will it be right??? Also I don’t understand how can I mock ISomeInterface. I need to test prop2 which depends on prop1. If I type:
[TestMethod]
public void Prop2ShouldReturnTwoValueIfSomeSettingEqualsSetting2()
{
var moqSettings = new Mock<ISomeInterface>();
moqSettings.Setup(p => p.Prop1).Returns("setting2");
...
}
it will not change anything, because moqSettings.Object.Prop2 will be null. And, I’m not sure, but I think it’s wrong to do like that))) So how can I test all cases in prop2???
P.S. For mocking I use Moq.
P.P.S. Sorry for my English))) I hope I explained clearly what i need…
I think your class has several responsibilities – reading configuration, and generating some values depending on configuration settings. If you split those responsibilities, then you can mock your application settings. Create some interface like
ISomeConfigurationImplement it this way:
And inject this interface to your
SomeClass:}
Now you can mock your configuration without problems: