TDD with Web Config - c#

All great stories they always start with those 4 magical words... I have inherited a system... no wait! that isn't right!
Anyway with my attempt at humour now passed I have not so much been given more I have to support an existing service.
There are many many issues when it comes to using this service, as an example one is to create a record of a person, you need to call 4 different parts of the services.
So, getting together with my Manager we decided that we need to stick another layer on top to add a facade to the common requests, to simplify the number things and the correct order to do them when creating a new site.
My question starts here if anyone wants to avoid the above waffle
So I want to use TDD on the work I am doing, but the service I have inherited (which will become our Data layer) has been strongly coupled with a database connection string located in a specific connetionstring node in the Web.Config.
Problem I have is, to decouple the service from the Config file will take weeks of my time which I do not have.
So I have had to add and App.Config file with the expected node into my Test project.
Is it ok to do this, or should I start investing some time to decouple the database config from the datalayer?

I agree that you should probably look into using Dependency Injection as your working your way through the code to decouple your app from the config, however, I also understand that doing that is not going to be an easy task.
So, to answer your question directly, no, there is nothing wrong with adding a config file to support your tests. This is actually quite common for unit testing legacy systems (legacy being an un-tested system). I have also, when left with no other option, resorted to utilizing reflection to "inject" fake configuration values into the ConfigurationManager in order to test code that is reading configuration values, but this is probably a last resort.

Try using Dependancy Injection to mock up your DataLayer.
In TDD you are not (necessarily) testing your datalayer and database but the BusinessLogic.
Some links:
SO best practices of tdd using c# and rhinomocks
TDD - Rhino Mocks - Part 1 - Introduction

You can use Dependency Injection to "untie" your code from web.config (or app.config for that matter):
http://weblogs.asp.net/psteele/archive/2009/11/23/use-dependency-injection-to-simplify-application-settings.aspx

As you mentioned Dependency Injection is the way to go. You also want to make sure that your consumers of your configuration object are not dependent on your specific configuration implementation such as the ConfigurationManager, ConfigurationSections, etc. To see a full example using custom configuration you can have a look at my blog post on Configuration Ignorance but basically it comprises of.
Your configuration implementation be it using a ConfigurationSection or an XmlReader should be based on an interface that way you can easily mock out your properties and easily change your implementation at a later date.
public BasicConfigurationSection : ConfigurationSection, IBasicConfiguration
{
...
}
To tackle how the the configuration is retried we use a configuration provider, the configuration provider for a particular configuration knows how to retrieve it's configuration
public interface IConfigurationProvider<TConfiguration>
{
TConfiguration GetConfiguration();
}
public class BasicConfigurationProvider : IConfigurationProvider<IBasicConfiguration>
{
public IBasicConfiguration GetConfiguration()
{
return (BasicConfigurationSection)ConfigurationManager.GetSection("Our/Xml/Structure/BasicConfiguration");
}
}
If you are using Windsor you can then wire this up to Windsor's factory facility.
Hope that helps.

Related

How to use dummy class for external API at runtime (configurable)?

I need to fetch data from an external API, only accessible via VPN.
The development/test machine will not always be able to connect to the VPN.
The desired behaviour is to use two different implementations (one that calls the actual external API and one that acts as the real thing but returns dummy data). Which implementation to use will be configured via a flag in web.config
I've tried the IoC containers StructureMap and Unity and they both did the job but they only seem to be applicable for MVC, I'm looking for a generic solution that also works for web forms. And also, isn't it a bit overkill to use them for this isolated design problem!?
Is there a design pattern or best practice approach for this particular scenario?
IoC / dependency injection sounds like the correct approach, but you don't necessarily need a container for a simple scenario. The key is to have classes that depend on the API reference an interface IAPI, and pass it the actual implementation RealAPI or FakeAPI.
public class SomeClass
{
private readonly IAPI _api;
public SomeClass(IAPI api)
{
_api = api;
}
}
Now you should be able to switch out the implementation easily by passing a different object to MyClass. In theory, when you're using an IoC approach, you should only need to bind the interface to the implementation once, at the top level of the application.
isn't it a bit overkill to use them for this isolated design problem!?
They probably are. Those IoC containers only help you when you wrote loosly coupled code. If you didn't design your classes according to the SOLID principles for instance, those frameworks will probably only be in the way. On the other hand, which developer doesn't want to write loosly coupled code? In other words, IoC container solves a problem you might not have but it's a nice problem to have.
StructureMap and Unity [...] only seem to be applicable for MVC
Those ioc frameworks can be used in any type of application (as long as it is written in loosly coupled way). Some types of applications need a bit more work to plug a framework in, but it's always possible. StructureMap and Unity might only have integration packages for MVC, it's quite easy to use them in ASP.NET Web Forms as well.
Is there a design pattern or best practice approach for this
particular scenario?
What you're looking for is the Proxy pattern and perhaps the circuit breaker pattern.

Where should I store Logger code to reduce dependencies?

I'm using Log4Net to handle logging in my WPF application.
Currently, the logger is configured with the rest of the front-end code. I have to pass a reference to the Service layer and the Repository layer if I want to be able to use the logger in these layers (I'll actually be using StructureMap for this). This means the back-end has a dependency on the front-end and I don't like that.
I'm wondering how best to handle this? Should I configure the logger in the Repository layer?
log4net LogManager.GetLogger(string name) will return an existing logger instance if it has already been created (e.g., in another layer), so there is no need to pass logger objects around.
You do need to be aware of multiple threads/processes trying to write to the same log file at the same time. You can use the log4net MinimalLock, or try this third party solution. Neither is ideal (the codeproject one is inefficient and still hits concurrency problems). I have ended up writing my own (which unfortunately is not publicly available).
Logging is a common cross-cutting concern that I have seen handled in several different ways. The simplest method is to create a static class that lives in a common assembly that is shared by all the layers.
However, since you are using StructureMap for your IoC, a better solution would be to configure StructureMap to inject your logger class (which might be configured as a singleton, depending on your needs) into each instance created. I personally prefer property injection for such cross-cutting concern classes, so that constructors don't get cluttered, but that's a matter of preference.

Using Provider Pattern - Multiple Abstract Classes

Created a group of related providers using the provider pattern. Now would like to enhance my providers due to new requirements given to me. The providers were created for a bunch of customers who integrate with our web services. Now some of the same customers would like to integrate with us using a web page. Going thru our web page the front end logic of course would be different but half of the provider logic would be the same. So I was thinking of adding another abstract class in particular customers provider to handle web page integration with provider. Here's a code ex using possible enhancement:
//Same Customer provider dll
//Methods defined for handling web service integration
public abstract class XMLBaseProvider : ProviderBase
//Methods defined for handling web page integration logic
public abstract class XMLWebPageBaseProvider : XMLBaseProvider
Now in the app.config I define another provider section that points to XMLWebPageBaseProvider along with a new provider name. This works but an wondering am I abusing the provider pattern coding it this way? Is there any concerns or gotchas I should be worried about by doing this. Has anybody here implemented this provider pattern like I described above?
Also note we probably will get more customers who will integrate with us using the web page integration. I would just hate having to keep adding more and more providers(dlls) to solution.
Thanks,
DND
I think your ideas are good. For what you described, your design will work fine. As one of the commentators noted, though, the requirements might expand into JSON. In my experience, the need for different formats always grows over time. When that happens, inheritance becomes quite brittle. The class hierarchy will grow to more and more levels of abstract classes. In the end, it will be difficult to manage.
The commentator suggested using composition and I agree. A strategy or visitor pattern will likely serve you better over the long run.
If the application is critical to the business and the business is growing, consider going a step further. Move as much of the provider logic as possible out of the code and into a configuration file or configuration database. This will be a big win in the long run because it minimizes the amount of code that must be change when the requirements grow. Changing the code risk creating bugs, mandates a new build and deployment, etc. Changing some data is much easier and less risky.
This strategy is generally referred to as data-driven programming. Have a look at this question.

Mocking without injection

(C#, WCF Service, Rhino Mocks, MbUNit)
I have been writing tests for code already in place (yes I know its the wrong way around but that's how its worked out on my current contract). I've done quite a bit of re-factoring to support mocking - injecting dependencies, adding additional interfaces etc - all of which have improved the design. Generally my testing experience has been going well (exposing fragility and improving decoupling). For any object I have been creating the dependant mocks and this sits well with me and makes sense.
The app essentially has 4 physical layers. The database, a repository layer for data access, a WCF service that is connected to the repository via a management (or business logic) layer, so top down it looks like this;
WCF
Managers
Repository
Database
Testing the managers and repository layer has been simple enough, mocking the dependencies with Rhino Mocks and injecting them into the layer under test as such.
My problem is in testing the top WCF layer. As my service doesn't have the constructor to allow me inject the dependencies, I'm not sure how I go about mocking a dependency when testing the public methods (ServiceContracts) on the service.
I hope that's made sense and any help greatly appreciated. I am aware of TypeMockIsolator etc, but really don't want to go down that route both for budget and other reasons I won't go into here. Besides I'm sure there are plenty of clever 'Stackers' who have the info I need.
Thanks in advance.
Is there a specific reason you cant have a constructor on your service?
If not, you can have overloaded constructors with a default constructor wiring up the defaults and one parametrized constructor with your dependencies. You can now test the parametrized ctor and rely on the default ctor for creating the instance in production.
public MyService() : this(new DefaultDep1(), new DefaultDep2())
{
}
public MyService(IDep1 d1, IDep2 d2)
{
}
A better solution if you use dependency injection would be to use the WCF IInstanceProvider interface to create your service instance and provide the needed dependencies via that injection point. An example using Structure Map can be found here.
You could make the WCF services a thin layer over the 'managers', so they have little or no logic in them which needs testing. Then don't test them and just test the managers. Alternatively, you could achieve a similar effect by having another 'service' layer which contains the logic from the services, which can be tested, and make the actual WCF code just pass through to that.
Our WCF service gets all its dependencies from a Factory object, and we give the service a constructor which takes IFactory. So if we want to write a test which mocks one of the dependencies, say an IDependency, we only need to inject a mock factory, which is programmed to give mocked IDependency object back to the service.
If your using an inversion of control (IoC), such as Unity, AutoFac or Castle Windsor, and a mocking framework (eg. Moq, NMock, RhinoMocks) this is simple enough as long as you have the right design.
For a good tutorial on how to do it with RhinoMock and Windsor, take a look at this blog article - http://ayende.com/Blog/archive/2007/02/10/WCF-Mocking-and-IoC-Oh-MY.aspx
If you're using Castle Windsor, take a look at the WCF facility, it lets you use non-default constructor and inject dependencies into your services, among other things.

How many levels of abstraction do I need in the data persistence layer?

I'm writing an application using DDD techniques. This is my first attempt at a DDD project. It is also my first greenfield project and I am the sole developer. I've fleshed out the domain model and User interface. Now I'm starting on the persistence layer. I start with a unit test, as usual.
[Test]
public void ShouldAddEmployerToCollection()
{
var employerRepository = new EmployerRepository();
var employer = _mockery.NewMock<Employer>();
employerRepository.Add(employer);
_mockery.VerifyAllExpectationsHaveBeenMet();
}
As you can see I haven't written any expectations for the Add() function. I got this far and realized I haven't settled on a particular database vendor yet. In fact I'm not even sure it calls for a db engine at all. Flat files or xml may be just as reasonable. So I'm left wondering what my next step should be.
Should I add another layer of abstraction... say a DataStore interface or look for an existing library that's already done the work for me? I'd like to avoid tying the program to a particular database technology if I can.
With your requirements, the only abstraction you really need is a repository interface that has basic CRUD semantics so that your client code and collaborating objects only deal with IEmployerRepository objects rather than concrete repositories. You have a few options for going about that:
1) No more abstractions. Just construct the concrete repository in your top-level application where you need it:
IEmployeeRepository repository = new StubEmployeeRepository();
IEmployee employee = repository.GetEmployee(id);
Changing that in a million places will get old, so this technique is only really viable for very small projects.
2) Create repository factories to use in your application:
IEmployeeRepository repository = repositoryFactory<IEmployee>.CreateRepository();
IEmployee employee = repository.GetEmployee(id);
You might pass the repository factory into the classes that will use it, or you might create an application-level static variable to hold it (it's a singleton, which is unfortunate, but fairly well-bounded).
3) Use a dependency injection container (essentially a general-purpose factory and configuration mechanism):
// A lot of DI containers use this 'Resolve' format.
IEmployeeRepository repository = container.Resolve<IEmployee>();
IEmployee employee = repository.GetEmployee(id);
If you haven't used DI containers before, there are lots of good questions and answers about them here on SO (such as Which C#/.NET Dependency Injection frameworks are worth looking into? and Data access, unit testing, dependency injection), and you would definitely want to read Martin Fowler's Inversion of Control Containers and the Dependency Injection pattern).
At some point you will have to make a call as to what your repository will do with the data. When you're starting your project it's probably best to keep it as simple as possible, and only add abstraction layers when necessary. Simply defining what your repositories / DAOs are is probably enough at this stage.
Usually, the repository / repositories / DAOs should know about the implementation details of which database or ORM you have decided to use. I expect this is why you are using repositories in DDD. This way your tests can mock the repositories and be agnostic of the implementation.
I wrote a blog post on implementing the Repository pattern on top of NHibernate, I think it will benefit you regardless of whether you use NHibernate or not.
Creating a common generic and extensible NHiberate Repository
One thing I've found with persistence layers is to make sure that there is a spot where you can start doing abstraction. If you're database grows, you might need to start implementing sharding and unless there's already an abstraction layer already available, it can be difficult to add one later.
I believe you shouldn't add yet another layer below the repository classes just for the purpose of unit testing, specially if you haven't chosen your persistence technology. I don't think you can create an interface more granular than "repository.GetEmployee(id)" without exposing details about the persistence method.
If you're really considering using flat text or XML files, I believe the best option is to stick with the repository interface abstraction. But if you have decided to use databases, and you're just not sure about the vendor, an ORM tool might be the way to go.

Categories