How can I drown the Properties.Settings object when the unit test is in a different assembly?

I have an object containing references from the values ​​of Properties.Settings.Default... and I need to stub them in the unit test for this object.

Unfortunately, the type of the settings object is declared as internal , so I cannot access it from the unit test project.

How can I fill in the return values ​​for these properties? I use Rhino Mocks for ridicule.

+4
source share
3 answers

In general, I would not do that. Instead of having your “internal” objects actually read Properties.Settings.Default, declare them the cconfigurable property (either at build time or through the properties), and another piece of code fills them.

Thus, you can test everything except the default reading material in your unit tests, and you will become less connected with the way of reading the default values, which simplifies the transition of the mechanism in the future.

+7
source

Another piece of advice that may be useful for solving an internal problem is to selectively make your internal code visible to your unit tests. In the test code, open your AssemblyInfo.cs and add something like the following:

 #if UNITTEST [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("YourUnitTestAssembly")] #endif 

Then you just need the UNITTEST character defined in your assembly, and your test assembly will be able to view all the internal elements.

+3
source

I know this is an old question, but I thought I would add my solution as my easiest and could help someone.

The created settings class is a partial class, we can use it 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 the test, create a class that inherits from ISettings and install a new implementation.

If your tests are found in a separate project, you will need to add another class to publish it. We cannot change the settings file to public, because it will simply be overwritten the next time you change or add a value.

0
source

All Articles