C#: Run each unit test with different configuration file - c#

I'm currently developing a plugin to use in any application, and the configuration of the plugin is done through the usage of either a web.config or an app.config file.
Now, I want to unit test my plugin. I want to test the different behaviour in various conditions:
For exmaple:
Only 1 single item should be marked as 'default'.
A collection of providers can be registered in the plugin, however the name must be unique, otherwise, a specific exception is thrown.
My question:
I have a unit test project and I want to test each method with another application configuration file, is this possible?
I've tried reading the file from ExeConfiguration, but I don't get it to work.
Thanks for the feedback.
Kr,

This is what we do (same as #THG) explained in his answer.
public interface IConfiguration
{
string SettingA { get; }
string SettingB { get; }
}
public class Configuration : IConfiguration
{
public string SettingA
{
get
{
return ConfigurationManager.AppSettings["SettingA"];
}
}
public string SettingB
{
get
{
return ConfigurationManager.AppSettings["SettingB"];
}
}
}
Then in your test
var config = MockRepository.GenerateStub<IConfiguration>();
config.Stub(x => x.SettingA).Return("Fred");

My recommendation is to mock the integration with the config file instead of using it directly. This approach offers much more flexibility and removes the need to worry about multiple config files.
You can either use a mocking framework or create you own layer of abstraction on top of the code that fetches the config values.

Related

IOptions Injection

It seems to me that it's a bad idea to have a domain service require an instance of IOptions<T> to pass it configuration. Now I've got to pull additional (unnecessary?) dependencies into the library. I've seen lots of examples of injecting IOptions all over the web, but I fail to see the added benefit of it.
Why not just inject that actual POCO into the service?
services.AddTransient<IConnectionResolver>(x =>
{
var appSettings = x.GetService<IOptions<AppSettings>>();
return new ConnectionResolver(appSettings.Value);
});
Or even use this mechanism:
AppSettings appSettings = new AppSettings();
Configuration.GetSection("AppSettings").Bind(appSettings);
services.AddTransient<IConnectionResolver>(x =>
{
return new ConnectionResolver(appSettings.SomeValue);
});
Usage of the settings:
public class MyConnectionResolver
{
// Why this?
public MyConnectionResolver(IOptions<AppSettings> appSettings)
{
...
}
// Why not this?
public MyConnectionResolver(AppSettings appSettings)
{
...
}
// Or this
public MyConnectionResolver(IAppSettings appSettings)
{
...
}
}
Why the additional dependencies? What does IOptions buy me instead of the old school way of injecting stuff?
Technically nothing prevents you from registering your POCO classes with ASP.NET Core's Dependency Injection or create a wrapper class and return the IOption<T>.Value from it.
But you will lose the advanced features of the Options package, namely to get them updated automatically when the source changes as you can see in the source here.
As you can see in that code example, if you register your options via services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); it will read and bind the settings from appsettings.json into the model and additionally track it for changes. When appsettings.json is edited, and will rebind the model with the new values as seen here.
Of course you need to decide for yourself, if you want to leak a bit of infrastructure into your domain or pass on the extra features offered by the Microsoft.Extensions.Options package. It's a pretty small package which is not tied to ASP.NET Core, so it can be used independent of it.
The Microsoft.Extensions.Options package is small enough that it only contains abstractions and the concrete services.Configure overload which for IConfiguration (which is closer tied to how the configuration is obtained, command line, json, environment, azure key vault, etc.) is a separate package.
So all in all, its dependencies on "infrastructure" is pretty limited.
In order to avoid constructors pollution of IOptions<>:
With this two simple lines in startup.cs inside ConfigureServices you can inject the IOptions value like:
public void ConfigureServices(IServiceCollection services)
{
//...
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddScoped(cfg => cfg.GetService<IOptions<AppSettings>>().Value);
}
And then use with:
public MyService(AppSettings appSettings)
{
...
}
credit
While using IOption is the official way of doing things, I just can't seem to move past the fact that our external libraries shouldn't need to know anything about the DI container or the way it is implemented. IOption seems to violate this concept since we are now telling our class library something about the way the DI container will be injecting settings - we should just be injecting a POCO or interface defined by that class.
This annoyed me badly enough that I've written a utility to inject a POCO into my class library populated with values from an appSettings.json section. Add the following class to your application project:
public static class ConfigurationHelper
{
public static T GetObjectFromConfigSection<T>(
this IConfigurationRoot configurationRoot,
string configSection) where T : new()
{
var result = new T();
foreach (var propInfo in typeof(T).GetProperties())
{
var propertyType = propInfo.PropertyType;
if (propInfo?.CanWrite ?? false)
{
var value = Convert.ChangeType(configurationRoot.GetValue<string>($"{configSection}:{propInfo.Name}"), propInfo.PropertyType);
propInfo.SetValue(result, value, null);
}
}
return result;
}
}
There's probably some enhancements that could be made, but it worked well when I tested it with simple string and integer values. Here's an example of where I used this in the application project's Startup.cs -> ConfigureServices method for a settings class named DataStoreConfiguration and an appSettings.json section by the same name:
services.AddSingleton<DataStoreConfiguration>((_) =>
Configuration.GetObjectFromConfigSection<DataStoreConfiguration>("DataStoreConfiguration"));
The appSettings.json config looked something like the following:
{
"DataStoreConfiguration": {
"ConnectionString": "Server=Server-goes-here;Database=My-database-name;Trusted_Connection=True;MultipleActiveResultSets=true",
"MeaningOfLifeInt" : "42"
},
"AnotherSection" : {
"Prop1" : "etc."
}
}
The DataStoreConfiguration class was defined in my library project and looked like the following:
namespace MyLibrary.DataAccessors
{
public class DataStoreConfiguration
{
public string ConnectionString { get; set; }
public int MeaningOfLifeInt { get; set; }
}
}
With this application and libraries configuration, I was able to inject a concrete instance of DataStoreConfiguration directly into my library using constructor injection without the IOption wrapper:
using System.Data.SqlClient;
namespace MyLibrary.DataAccessors
{
public class DatabaseConnectionFactory : IDatabaseConnectionFactory
{
private readonly DataStoreConfiguration dataStoreConfiguration;
public DatabaseConnectionFactory(
DataStoreConfiguration dataStoreConfiguration)
{
// Here we inject a concrete instance of DataStoreConfiguration
// without the `IOption` wrapper.
this.dataStoreConfiguration = dataStoreConfiguration;
}
public SqlConnection NewConnection()
{
return new SqlConnection(dataStoreConfiguration.ConnectionString);
}
}
}
Decoupling is an important consideration for DI, so I'm not sure why Microsoft have funnelled users into coupling their class libraries to an external dependency like IOptions, no matter how trivial it seems or what benefits it supposedly provides. I would also suggest that some of the benefits of IOptions seem like over-engineering. For example, it allows me to dynamically change configuration and have the changes tracked - I've used three other DI containers which included this feature and I've never used it once... Meanwhile, I can virtually guarantee you that teams will want to inject POCO classes or interfaces into libraries for their settings to replace ConfigurationManager, and seasoned developers will not be happy about an extraneous wrapper interface. I hope a utility similar to what I have described here is included in future versions of ASP.NET Core OR that someone provides me with a convincing argument for why I'm wrong.
I can't stand the IOptions recommendation either. It's a crappy design to force this on developers. IOptions should be clearly documented as optional, oh the irony.
This is what I do for my configuraition values
var mySettings = new MySettings();
Configuration.GetSection("Key").Bind(mySettings);
services.AddTransient(p => new MyService(mySettings));
You retain strong typing and don't need need to use IOptions in your services/libraries.
You can do something like this:
services.AddTransient(
o => ConfigurationBinder.Get<AppSettings>(Configuration.GetSection("AppSettings")
);
Using Net.Core v.2.2, it's worked for me.
Or then, use IOption<T>.Value
It would look something like this
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
I would recommend avoiding it wherever possible. I used to really like IOptions back when I was working primarily with core but as soon as you're in a hybrid framework scenario it's enough to drive you spare.
I found a similar issue with ILogger - Code that should work across frameworks won't because I just can't get it to bind properly as the code is too dependent on the DI framework.

Dependency injection based on configuration?

I am working on an app which uses active directory to retrieve users. Sometimes I need to work on the app but AD is not available. I use a wrapper class to retrieve the AD user. I would like to inject a different class based on the configuration. I was thinking on using an appSetting that would tell me the current configutarion and decide what type to use when injecting. Is it possible to get the current configuration without using a Web.config transform? Is it possible to inject objects using Unity based on Web.config transformations? Can you recommend a better approach?
[UPDATE]
I have a user repository class that loads the users from AD. All I need is to be able to change the implementation of this repository class so that when AD is unavailable I can load the users a different way. This would only be used for development, production would always access AD and retrieve users.
You can use preprocessor directives:
#if DEBUG
// register fake repository
#else
// register AD repository
#endif
Well, Dependency Injection is incredibly powerful, agile, and creates a separation of concerns. The pitfall in your approach will come from validation. You see, with this approach you have to choose a concrete implementation.
So how will you call those two classes?
public class LogToText : ILogger
{
public void LogMessage(string message) { }
}
public class LogToEvent : ILogger
{
public void LogMessage(string message) { }
}
You have these two implementations, but when you pass the interface to:
public class AD
{
public AD(ILogger logger) { }
}
So the question will be do you feel that you can properly validate to choose the proper implementation effectively. Otherwise, Dependency Injection may not work well. We don't entirely know the usage or goal, so our advice may not be truly beneficial. Hopefully you see what I mean, because you'll have to see if you can't test a particular way.
You could use an Abstraction for this:
public interface IPersonService
{
IEnumerable<Person> Find(PersonSearchParameters searchParams);
Person GetByAccountName(string accountName);
[ETC...]
}
Then both your AD and Development implements this interface.
To make things easier, I suggest using StructureMap IoC, so you can easily do this:
x.For<IPersonService>.Use<ActiveDirectoryPersonService>(); //for production
or
x.For<IPersonService>.Use<MockPersonService>(); //for development
When using this you can, for instancce:
public class TestController : Controller
{
IPersonService _service;
public TestController(IPersonService service)
{
_service = service;
}
}
Instead of using an XML file for configuration in this case, I suggest using the Fluent code of Structure Map, it's better when refactoring and to avoid mistyping because it compiles.
StructureMap:
http://structuremap.net
Easy Installable via NuGET
A different approach would be to use the build configuration, read back from the assembly.
var buildConfiguration = typeof(Program).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>()?.Configuration;
if (buildConfiguration == "Debug")
{
// register fake repository
}
else
{
// register AD repository
}
Then it is safer to apply refactorings or automatic code clean up (e.g. ReSharper etc.). Depending on your current configuration, code cleanup can otherwise remove unused usings. What then leads to build issues if an other configuration is used.

Unit test SerializableConfigurationSection programmatically

I'm using strongly typed configuration sections in my project and want to unit test a particular area which throws an exception when a setting isn't set-up correctly.
A snippet of the configuration class:
public class EmailSettings : SerializableConfigurationSection, IEmailSettings
{
[ConfigurationProperty("from", IsRequired = true)]
public string From
{
get
{
...
}
set
{
...
}
}
...
}
Sample test method:
[TestMethod]
public void something_describing_this_test()
{
EmailSettings settings = new EmailSettings();
settings.From;
}
I expect that SerializableConfigurationSection and its inners are looking for a web.config (or similar) to read xml config from.
How can I get in the middle and 'mock' the configuration to enable me to pipe custom values to test for certain conditions? This question (using ConfigurationManager methods) appears to do it via a physical config file in the assembly - is this the only way or can I get in there programmatically?
You could generate one in your test fixture setup, and then load it like described in the answer to this question:
Loading custom configuration files

How can I horribly twist a c# project to read its class library's app.config files

So let me start off by saying "I know this isn't a best practice" and that I do not want to add the information from the app.config files to the web.config file... I've got a project that is a class library itself and it will be using a lot of class libraries as well.
Typically in my unit test project (used for testing) or my web project (that uses the lib in production) I have to add all of the configuration information. These libraries aren't going to be called differently from each project so I'm looking for a way to get the calling project to read the callee project's config file.
I've looked online and the only two things I've found so far are:
1) Don't do it. You need to add the information to the calling project's config file
example a) Read from App.config in a Class Library project
example b) Class Library project in ASP.NET reading from web.config and not app.config
example c) .Net app.config in library project
2) You shouldn't do it but I know how (no how to included :/)
example a) app.config for a class library
I've been doing it the "right" way for a while and that has left me with lots of web.config and test project config files with info duplicated from class lib app.config files. I really do think that there is a specific, justified use case for doing this.
Thanks!
The best practice that I know of is to avoid direct dependency on app.config/web.config from classes in your library, or maybe even classes in general. That doesn't mean that you don't use app.config. It means that your classes don't know they're using it.
For example,
public class MyClassThatDependsOnSomeSettings
{
private readonly ISettings _settings;
public MyClassThatDependsOnSomeSettings(ISettings settings)
{
_settings = settings;
}
public void DoSomething()
{
var settingA = _settings.SettingA;
}
}
public interface ISettings
{
int SettingA {get;}
string SettingB {get;}
}
Now you can consider MyClassThatDependsOnSomeSettings done. It doesn't require any access to a .config file. It just requires an instance of something that implements ISettings. That can read from .config.
public class SettingsFromConfiguration : ISettings
{
public int SettingA
{
get
{
string setting = ConfigurationManager.AppSettings["settingA"];
int value = 0;
int.TryParse(setting, out value);
return value;
}
}
public string SettingB
{
get { return ConfigurationManager.AppSettings["settingB"];}
}
}
Does it look like this just moves things around and does the same thing anyway? It does, almost. The big difference is that while you can use an implementation of ISettings that reads from app.config, you can also write other implementations. You can write one that uses hard-coded values, you could write a custom configuration section instead of using AppSettings, or if down the road you have an application with a JSON configuration file and no AppSettings your class can still work.
This applies the Dependency Inversion, which beneath everything means that classes should depend on abstractions (like interfaces) not concrete implementations.
Putting a requirement for ISettings in the constructor is called Dependency Injection, specifically constructor injection.

How to configure an object and override that configuration

I have the following interfaces and classes:
public interface ILoggingService { ... }
public class LoggingService {
public LoggingService(ILoggingRepository loggingRepository) { ... }
...
}
public interface ILoggingRepository { ... }
public class DatabaseLoggingRepository {
public DatabaseLoggingRepository(string ConnectionString) { ... }
...
}
public class FileLoggingRepository {
public FileLoggingRepository(string LogFilePath) { ... }
...
}
I'm refactoring my software to use Unity IoC framework and am looking for a way to pass the specific configuration to each ILoggingRepository implementation.
I think that the best way would be to change DatabaseLoggingRepository's and FileLoggingRepository's constructors to have no parameters at all and have them configured by some configuration file. However, because of my acceptance tests I would need a easy way to override these settings while running my tests.
Am I on the right track and if I am, which configuration files should I use? Alternative ways are welcome as well.
What we've decided to do is create a class, in your case it would be LoggingConfiguration, and have that passed to the constructo of the repository. If you resolve using Unity it will instantiate this class using Activator, wuthout having to register it. In your tests however, you just greate a new instance of a derived configuration class, providing different values.
Does it makes sense? Should I clarify more?
Update: I've decided to provide some additional clarification. So, you already have two implementations, and now you want each configuration to query for its proper configuration setting.
I would extend the ILoggingRepository's constructor to look like this:
public ILoggingRepository(ILoggingConfigurationProvider confProvider);
You can then create one implementation for your normal operation which has two properties:
public LoggingConfigurationProvider : ILoggingConfigurationProvider {
public LoggingConfigurationProvider() {
// load both values from configuration file
}
public string LogPath { get; set; }
public string ConnectionString { get; set; }
}
When you instantiate your class via normal IoC operation this will get resolved by the container and you'll configuration options will get loaded from the conf file. When you however want to do Unit tests you:
1) Create a new "Mock" implementation
public class MockLoggingConfigurationProvider : ILoggingConfigurationProvider {
public MockLoggingConfigurationProvider() {
// set both values to a test value
}
public string LogPath { get; set; }
public string ConnectionString { get; set; }
}
Now you can either create the repository using a constructor:
new LoggingRepository(new MockLoggingConfigurationProvider());
or if you want the whole IoC mechanism to be used, you simply (when setting up the container) register this implementation of the interface. Because the unit tests are separate, you don't share the registrations right? So that should give you what you need, the ability to change this settings depending on weather they are being executed as a unit test or not.
In real life, I wouldn't even bother with this, and just create a mock logging repository and have it write somewhere else. Unless you want to test the repository to a test database/file. In which case I'd do as specified.
Hope it helps.
As a design suggestion does not force IoC to deal with configuration stuff. Each logger should manage the configuration the way they prefer in its implementation. IoC should just inject the logger. For the unit/integration test, in both case you should e able to provide a configuration for the logger, for example using log4net I'm used to configure the logging subsystem in the Startup of the test by the api, and I create an appender that write just everithing on the console. You can't Insolate configuration by IoC since each possible logging system does not necessary share a contract for the Configuration part.

Categories