How can I stub the Properties.Settings object when the unit test is in a different assembly?
I have an object the references a bunch of Properties.Settings.Default...
values and I need to stub these in the unit test for this object.
Unfortunately the type for the settings object is declared as internal
and so I can开发者_运维百科't access it from the unit test project.
How can I stub up the return values for these properties? I'm using Rhino Mocks for mocking.
In general, I wouldn't. Instead of your "inner" objects actually reading Properties.Settings.Default, have them declare a cconfigurable property (either at construction time, or via properties), and have another piece of code populate them.
That way, you can test everything but the default reading stuff in your unit tests, and you become less coupled to a way of reading the defaults, making it easier to switch the mechanism in the future.
Also another tip that you may find useful to get around the internal problem, you can actually selectively make your internal code visible to your unit tests. In the code you are testing, open up your AssemblyInfo.cs and add something like the following:
#if UNITTEST
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("YourUnitTestAssembly")]
#endif
Then you just need the UNITTEST symbol defined in your build and your test assembly will be able to view all internal members.
I know this is an old question but I thought I would add in my solution as its simple and could help someone.
The settings class created is a partial class, we can leverage this to create our own implementation of Default.
Create a new file in the Properties folder
internal partial class Settings : ISettings
{
private static ISettings _setInstance;
internal static ISettings Get
{
get
{
return _setInstance = _setInstance ?? Default;
}
set { _setInstance = value; }
}
}
Then when we use it elsewhere in the application we can call Settings.Get.. If you want to set the values from test, create a class that inherits from ISettings and set the new implementation.
If your tests are found in a separate project you will have to add another class to expose the setter to public. We cant change the settings file to public as this would just be overwritten the next time we change or add a value.
精彩评论