I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I’m not sure the ‘best practice’ in this case.
Simple Example
This class is defined in Assembly1:
public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings['stringProperty']; } }
This class is defined in Assembly2:
[TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } }
EDIT 1: I have answered this question with a potential solution but I’m not sure if it’s the ‘right way to go’. So if you think you have a better idea please post it.
This example isn’t really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?
EDIT 2: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.
Nothing, unless you are using that field. You don’t want over-specification via tests. In other words, there is no need to test that the assignment operator works.
If you are using that field in a method or something, call that method and assert on that.
Edit:
You shouldn’t be performing any logic in constructors.
Edit 2:
Don’t do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the
ConfigurationManager.AppSettingscall. Pass an instance of that SettingsReader class into the constructor ofClass2Test. Then, in your unit test, you can mock yourWebConfigSettingsReaderand stub out a response to any calls you might make to it.