Mock implementation for use in automatic UI testing - c#

I am working on adding basic automatic UI tests to the block of unit tests we run with each nightly build. We used MSTest coded UI and created a script.
The code-behind is dependent upon IClientManager which both the real manager and mock implement.
My problem is that I don't know how to switch automatically between the real and mock implementations inside the button click handler, when running a test.
My two other constraints are that I can't have a dependency on the mock assembly in the code-behind and that I can't use a DI framework, since the client is "security conscious" and getting a framework approved might take months.
Is there any way of doing this manually, and hopefully, not a bigger problem than the problem I am looking to solve?
Thank you!

You could build your own simple object container if you can't use a third party one (which is silly but I understand, I've been there before)
here is something that I whipped up that could get you started... haven't tested it and it is really rough, but hopefully you get the idea
public static class ObjectFactory
{
static IDictionary<Type, object> _factory = new Dictionary<Type, object>();
public static void Register<T>(Func<T> builder)
{
if (_factory.ContainsKey(typeof(T)))
_factory[typeof(T)] = builder;
else
_factory.Add(typeof(T), builder);
}
public static T GetInstance<T>()
{
if (_factory.ContainsKey(typeof(T)))
throw new ArgumentException(string.Format("Type <{0}> not registered in ObjectFactory", typeof(T).Name));
return ((Func<T>)_factory[typeof(T)])();
}
}
public interface IClientManager { }
public class RealClientManager : IClientManager { }
public class MockClientManager : IClientManager { }
public class MyView
{
public MyView()
{
// probably better to do this registry in some sort of application initialization
ObjectFactory.Register<IClientManager>(() => new RealClientManager());
}
public void SomeMethodThatNeedsClientManager()
{
var clientManager = ObjectFactory.GetInstance<IClientManager>();
}
}
public class MyTester
{
[TestMethod()]
public void SomeTest()
{
var view = new MyView();
// swap the client manager in the test
ObjectFactory.Register<IClientManager>(() => new MockClientManager());
// Asserts
}
}
you can see that if you've used StructureMap or some other DI container before they do a lot of the same thing with a lot of added niceties such as traversing your object graph and registering objects automatically based on conventions, managing object lifecycles, scoping of containers, etc... a lot of this stuff you could implement yourself too... but you should just really used a tried and true solution such as StructureMap

Related

Limit Ninject.MockingKernel to mocking classes in my own namespaces only

I've just switched to using the NInject.MockingKernel extension for my tests (NSubstitute).
However, it makes very hard to run my Web API integration tests because it will return mocks for all Web API interfaces also.
Can I automatically limit its application only to namespaces of my own?
I don't see how that is possible out of the box. Although it's not very hard to create such a kernel on your own.
This sample is of course very minimalistic though, but it should show you how it could be done. Or maybe there is someone with more knowledge of the Ninject internals.
public class NamespaceFilteringMockMissingBindingsResolver : MockMissingBindingResolver
{
public NamespaceFilteringMockMissingBindingsResolver(IMockProviderCallbackProvider mockProviderCallbackProvider)
: base(mockProviderCallbackProvider)
{
}
protected override bool TypeIsInterfaceOrAbstract(Type service)
{
return base.TypeIsInterfaceOrAbstract(service) && service.Namespace != null && service.Namespace.StartsWith("YourNamespace");
}
}
public class CustomNSubstituteMockingKernel : NSubstituteMockingKernel
{
public CustomNSubstituteMockingKernel()
{
this.AddComponents();
}
public CustomNSubstituteMockingKernel(INinjectSettings settings, params INinjectModule[] modules)
: base(settings, modules)
{
this.AddComponents();
}
private new void AddComponents()
{
this.Components.RemoveAll<IMissingBindingResolver>();
this.Components.Add<IMissingBindingResolver, SingletonSelfBindingResolver>();
this.Components.Add<IMissingBindingResolver, NamespaceFilteringMockMissingBindingsResolver>();
}
}
Update
You are right, you don't need to create your own kernel. You can also do it like this.
var kernel = new NSubstituteMockingKernel();
kernel.Components.RemoveAll<IMissingBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, SingletonSelfBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, NamespaceFilteringMockMissingBindingsResolver>();
Creating your own kernel might just be more handy than always writing those extra lines. Or you create some kind of factory method.

What is Ninject and when do you use it?

I have been helping a few friends on a project and there is a class that uses Ninject. I am fairly new to C# and I have no idea what that class is doing, which is why I need to understand Ninject. Can anyone explain what Ninject is and when does one use it(with example if possible)? Or if you can point to some links that would be great too.
I tried this question: Ninject tutorials/documentations? but it didn't really help a beginner like me.
Ninject is dependency injector for .NET, practical realisation of pattern Dependency Injection (form of Inversion of Control pattern).
Suppose you have two classes DbRepository and Controller:
class Controller {
private DbRepository _repository;
// ... some methods that uses _repository
}
class DbRepository {
// ... some bussiness logic here ...
}
So, now you have two problems:
You must initialize _repository to use it. You have several options for doing this:
Manually, within the constructor. But what if the constructor of DbRepository changes? You would need to rewrite your Controller class because code it's dependent upon was changed. It's not hard if you have only one Controller, but if you have a couple of classes that have a dependency on your Repository you have a real problem.
You can use a service locator or factory. But now you have a dependency on your service locator. You have a global service locator and all code must use it. How you will you change the behavior of your service locator when you need to use it in one part of your code for activation logic but for something else in another part of your code? There is only one way - passing the service locator through constructors. But with more and more classes you will need to pass it more and more times. Anyway, it's a good thought but in the long run, it's a bad idea.
class Controller {
private DbRepository _repository;
public Controller() {
_repository = GlobalServiceLocator.Get<DbRepository>()
}
// ... some methods that uses _repository
}
You can use dependency injection. Look at the code:
class Controller {
private IRepository _repository;
public Controller(IRepository repository) {
_repository = repository;
}
}
Now when you need your controller you write: ninjectDevKernel.Get<Controller>(); or ninjectTestKernel.Get<Controller>();. You can switch beetween dependency resolvers as fast as you want. See? It's simple, you don't need to write a lot.
You can't create unit tests for it. Your Controller has a dependency on DbRepository and if you want to test some method that uses repository, your code will go to the database and ask it for data. That's slow, very slow. If your code in DbRepository changes, your unit test on Controller will fall. Only integration test must warn you of 'problems' in this case. What you need in unit tests - is to isolate your classes and test only one class in one test (in ideal - only one method). If your DbRepository code fails, you will think that Controller code failed - and that's bad (even if you have tests for DbRepository and Controller - they both will fail and you can start from the wrong place). It takes a lot of time to determine where the error really is. You need to know that class A is ok, and it was class B where something failed.
When you want to replace DbRepository with something else in all your classes, you have to do a lot of work.
You can't easily control the lifetime of DbRepository. An object of this class is created on initialization of Controller and deleted when Controller is deleted. There is no sharing between different instances of the Controller class and there is no sharing between other classes. With Ninject you can simply write:
kernel.Bind<IRepository>().To<DbRepository>().InSingletonScope();
A special feature of dependency injection - agile development! You describe that your controller uses a repository with interface IRepository. You don't need to write DbRepository, you can simply create a MemoryRepository class and develop Controller while another person develops DbRepository. When work on DbRepository is finished, you just rebind in your dependency resolver that default IRepository is now DbRepository. Have a lot of controllers? All of them will now use DbRepository. That's cool.
Read more:
Inversion of control (wiki)
Dependency injection (wiki)
Inversion of Control Containers and the Dependency Injection pattern (Martin Fowler)
Ninject is an Inversion of Control container.
What does it do?
Suppose you have a Car class that depends on a Driver class.
public class Car
{
public Car(IDriver driver)
{
///
}
}
In order to use the Car class you build it like so:
IDriver driver = new Driver();
var car = new Car(driver);
A IoC containter centralizes the knowledge about how to build classes. It is a central repository that knows a few things. For example, it knows that the concrete class that you need to use to build a car is a Driver and not any other IDriver.
For example, if you are developing a MVC application, you can tell Ninject how to build your controllers. You do so by registering which concrete classes satisfy specific interfaces. At run time Ninject will figure out which classes are needed to build the required controller, and all behind the scenes.
// Syntax for binding
Bind<IDriver>().To<Driver>();
This is beneficial because it lets you build systems that are more easily unit testable. Suppose that Driver encapsulates all database access for Car. In a unit test for Car you can do this:
IDriver driver = new TestDriver(); // a fake driver that does not go to the db
var car = new Car(driver);
There are entire frameworks that take care of automatically creating testing classes for you and they are called mocking frameworks.
For more information:
GitHub/Ninject Home
Inversion of Control
Inversion of Control Containers and the Dependency Injection pattern
Mock Object
Other answers are great but I would also like to point out this Implementing Dependency Injection using Ninject article.
This is one of the best articles I ever read which explains Dependency Injection and Ninject with a very elegant example.
Here's the snippet from the article:
Below Interface will be implemented by our (SMSService) and (MockSMSService), basically the new Interface (ISMSService) will expose the same behaviors of both services as the code below:
public interface ISMSService
{
void SendSMS(string phoneNumber, string body);
}
(SMSService) implementation to implement the (ISMSService) interface:
public class SMSService : ISMSService
{
public void SendSMS(string mobileNumber, string body)
{
SendSMSUsingGateway(mobileNumber, body);
}
private void SendSMSUsingGateway(string mobileNumber, string body)
{
/*implementation for sending SMS using gateway*/
Console.WriteLine("Sending SMS using gateway to mobile:
{0}. SMS body: {1}", mobileNumber, body);
}
}
(MockSMSService) with totally different implementation using the same interface:
public class MockSMSService :ISMSService
{
public void SendSMS(string phoneNumber, string body)
{
SaveSMSToFile(phoneNumber,body);
}
private void SaveSMSToFile(string mobileNumber, string body)
{
/*implementation for saving SMS to a file*/
Console.WriteLine("Mocking SMS using file to mobile:
{0}. SMS body: {1}", mobileNumber, body);
}
}
we need to implement a change to our (UIHandler) class constructor to pass the dependency through it, by doing this, the code which uses the (UIHandler) can determine which concrete implementation of (ISMSService) to use:
public class UIHandler
{
private readonly ISMSService _SMSService;
public UIHandler(ISMSService SMSService)
{
_SMSService = SMSService;
}
public void SendConfirmationMsg(string mobileNumber) {
_SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
}
}
Now, we have to create a separate class (NinjectBindings) which inherits from (NinjectModule). This class will be responsible to resolve dependencies at run time, then we’ll override the load event which is used to configure the binding in it. The nice thing about Ninject is that we do not need to change our code in (ISMSService), (SMSService), and (MockSMSService).
public class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<ISMSService>().To<MockSMSService>();
}
}
Now in UI form code, we’ll use the binding for Ninject which will determine which implementation to use:
class Program
{
static void Main(string[] args)
{
IKernel _Kernal = new StandardKernel();
_Kernal.Load(Assembly.GetExecutingAssembly());
ISMSService _SMSService = _Kernal.Get<ISMSService>();
UIHandler _UIHandler = new UIHandler(_SMSService);
_UIHandler.SendConfirmationMsg("96279544480");
Console.ReadLine();
}
}
Now the code is using the Ninject Kernal to resolve all chain of dependencies, if we want to use the real service (SMSService) in Release mode (on production environment) instead of the mock one, we need to change on the Ninject binding class (NinjectBindings) only to use the right implementation or by using the #if DEBUG directive as below:
public class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
#if DEBUG
Bind<ISMSService>().To<MockSMSService>();
#else
Bind<ISMSService>().To<SMSService>();
#endif
}
}
Now our binding class (NinjectBindings) is living on the top of all our execution code and we can control the configuration easily in once place.
Also, see What is Inversion of Control? some very simple examples are mentioned to understand IoC.
You have to understand the Dependency Injection(DI) first. Notice here,
public interface IService
{
void Serve();
}
public class Service1 : IService
{
public void Serve() {
Console.WriteLine("Service1 Called");
}
}
public class Service2 : IService
{
public void Serve() {
Console.WriteLine("Service2 Called");
}
}
public class Service3 : IService
{
public void Serve() {
Console.WriteLine("Service3 Called");
}
}
public class Client
{
private IService service;
public Client(IService _service) //Constructor injection
{
service = _service;
}
public void ServeMethod() {
service.Serve(); //Notice here, this Serve() method has no idea what to do.
} // runtime will assign the object, that is Ninject
}
class Program
{
static void Main(string[] args)
{
IService s1 = new Service1(); //N.B. Ninject assigns object with interface
Client c1 = new Client(s1);
c1.ServeMethod();
IService s2 = new Service2(); //N.B. Ninject assigns object with interface
c1 = new Client(s2);
c1.ServeMethod();
IService s3 = new Service3(); //N.B. Ninject assigns object with interface
c1 = new Client(s3);
c1.ServeMethod();
Console.ReadKey();
}
}
// Ninject creates object in runtime for interface in runtime in ASP.NET MVC project.
/*
Output:
Service1 Called
Service2 Called
Service3 Called
*/

Using Dependency Injection outside of a Controller's constructor

So here's the issue, my mvc3 project uses Dependency Injection and has a base Generic IRepository class from which other repositories derive.
So I can co ahead and do this in a controller:
public class SomethingController
{
IOrderRepository repository;
public SomethingController(IOrderRepository repo)
{
this.repository = repo;
}
public ActionResult SaveOrder(Order order)
{
repository.add(order)
unitOfWork.CommitChanges(); // THIS works!
}
}
But now i need to use one of those repositories in a custom static non-controller like this:
static class OrderParser
{
private IOrderRepository repo;
public static DoWork()
{
repo = DependencyResolver.Current.GetService<IOrderRepository>();
var ordersInDB = repo.GetAllOrders(); //THIS works!
//But!
var ordersForInsertion = new List<Order>();
//do some backgroundworker magic
//fetch txt files from an ftp server
var ordersForInsertion = ParseTextFilesIntoOrders();
foreach order in ordersForInsertion
repo.add(order)
unitOfWork.CommitChanges();
// THIS doesnt commit anything into the database
// It also doesnt throw any exceptions
// and repo isnt null or any of that
}
}
So, as a test, i tried doing:
repo = DependencyResolver.Current.GetService<IOrderRepository>();
inside a controller class like in the first example to see if it also didnt commit stuff, and it doesn't. (Doing it the right way [injecting repositories and the unitOfWork trough the constructors] works!)
So it has to be something to do with the DependencyResolver, right?
Note: if there is any more code you need me to post, ask away and I'll edit it in here in a flash!
Note2: Thanx!
EDIT1:
Regarding w0lf's super fast answer
Here's some more info:
My OrderParser class implments a backgroundWorker which is supposed to:
Sleep for an hour
List all the files (plain txt files) in an FTP server.
Discard the ones that are already parsed into the db.
Parse the new files into Order objects.
Commit the objects into db.
Start all over and over till the power goes out or something :)
All that has to happen without any user action, meaning, the action is not originated from a controller, hence all I do is:
in my bootstrapper class
Initialise()
{
//Unrelated stuff
OrderParser.DoWork()
}
And that's also why I implemented it as a static class ( easily changable to a non-static )
EDIT2:
It would be something like:
class OrderParser
{
private IOrderRepository repo;
public OrderParser(IOrderRepository foo)
{
this.repo = foo;
}
public static DoWork()
{
//use repo var!
}
}
But then when i instance it in the bootstrapper Initialize() method, how would i do that, e.g.:
class bootstrapper
{
Initialize()
{
var parser = new OrderParser(/*how do i pass the dependency here?*/)
parser.DoWork();
}
}
EDIT3:
Here's some more testing, please bear with me!
Here's my OrderParser again:
class OrderParser
{
public OrderParser(IOrderRepository foo, IContext unitOfWork)
{
foo.getall();
foo.add(some_order);
unitOfWork.commit();
}
}
Test1:
public class SomeController
{
IOrderRepository repository;
public SomeController(IOrderRepository repo)
{
this.repository = repo;
}
public ActionResult SomeMethod(Order order)
{
repository.GetAll(); //WORKS
repository.add(order)
unitOfWork.CommitChanges(); // WORKS
}
}
TEST2:
class bootstrapper
{
Initialize()
{
//Build unity container..
//set resolver..
var parser = new OrderParser(container.Resolve<IOrderRepository>, container.Resolve<IContext>)
//can getAll, cant commit.
}
}
TEST3:
public class SomeController
{
IOrderRepository controllers_repository;
public SomeController(IOrderRepository repo)
{
this.controllers_repository = repo;
}
public ActionResult SomeMethod(Order order)
{
var parser = new OrderParser(DependencyResolver.Current.GetService<IOrderRepository>,
DependencyResolver.Current.GetService<IContext>)
//can do getall, no commits
var parser = new OrderParser(controllers_repository, controllers_icontext)
// obviously works (can getall and commit)
}
}
By the way, when i say "can't commit" it's not that i get an exception or the repositories are null, nope. the code runs as if it were okay, only the DB won't change.
One possible solution is to make the OrderParser class non-static and inject an instance of it in the constructor of the Controller that triggers the action (DoWork).
Then make OrderParser's constructor take an IOrderRepository parameter and the IoC container will gladly take care of it.
Also, beware of things like:
DependencyResolver.Current.GetService<ISomeInterface>();
This is called Service Locator and it's considered to be an anti-pattern. Avoid it if possible.
Basically, the only place where you should reference DependencyResolver.Current.GetService is your implementation of IControllerFactory that enables DI in the first place.
Update:
It would be best if you did this in another application than your MVC website. Two alternatives would be:
a Windows Service that performs that action based on a timer
a Console application that is run using Windows Task Scheduler every hour
These, being separate applications would have their own Composition roots that would deal with the object instantiation / dependency injection issue.
If, however, you are constrained to do this from your web app (for example - you have a hosting that only allows web apps), then you may find it acceptable to make an exception to the "Don't use the Dependencey Resolver directly" rule and do somehing like this on the application startup:
var runner = DependencyResolver.Current.GetService<OrderParsingRunner>();
runner.StartWorking();
Of course, the OrderParsingRunner class would look something like this:
public class OrderParsingRunner
{
private readonly OrderParser orderParser;
public OrderParsingRunner(OrderParser orderParser)
{
this.orderParser = orderParser;
}
public StartWorking()
{
TaskFactory.StartNew(() =>
{
DoWorkHourly();
});
}
private DoWorkHourly()
{
while(true)
{
Thread.Sleep(TimeSpan.FromHours(1));
orderParser.DoWork();
}
}
}
Disclaimer: I haven't actually compiled/run this code, I just wrote it to illustrate the concept.
Please note that this is a workaround rather than an actual solution. It's recommended that you use another application for the background tasks if possible.
You shouldn't need static helper classes when using DI. You can treat everything as a "service" and declare your dependencies in your constructor. That's how I think about it. Then everything just gets created for you as you need it.
So I would change your static class to a non-static and inject it where needed via the constructor.
Answer for Edit 2
Pass your container in to the bootstrap class.
class bootstrapper
{
    Initialize(DependencyResolver container)
    {
        var parser = new OrderParser(container.Resolve<IOrderRepository>());
        parser.DoWork();
    }
}
Edit
I would actually do this ...
var parser = container.Resolve<OrderParser>();
and let the dependency resolver figure everything out!
Since this is a background task, don't run this in a web application. Instead use a service or scheduled application in windows.
Youc an then resolve your reference during application initialization or using a [Dependency] attribute
http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.100).aspx
http://stackoverflow.com/questions/888479/using-unity-framework-inject-into-system-windows-forms-form-page

Linq: scoped DataContext, unit-of-work, repository

I have been researching about the unit-of-work and the repository pattern in C#. AFAIK, DataContext implements the unit of work pattern, and can be used to implement a repository interface. One last piece that's lacking in DataContext is a way to share this resource globally within a predefined scope.
I briefly looked at NCommon as a solution to this missing piece. Would you share your experience in NCommon, or recommend other solutions? Please also correct me if I have misunderstood. Thanks.
I always worked with DataContext in the same way NHibernate does: Having a static way to get it and different storages for storing it. For instance, it could be stored in the HttpContext.Current.Items collection for a web based application, or in Call.Context for the unit tests. When do you create the instance and when do you close it will depend on the scenario. Again, for web it make sense to do it on the Request_begin and Request_end events of your application. For unit tests, maybe on the setup and teardown.
Hope it helps.
Edit: Here's some implementation
public abstract class DataContextProvider
{
public abstract DataContext GetCurrent();
public abstract void OpenNew();
public void CloseCurrent()
{
var current = GetCurrent();
current.Dispose();
}
}
In your data context you add this:
public static DataContextProvider Provider { private get; set; }
public static DataContext Current { get { return Provider.GetCurrent(); } }
For web:
In your web project you put this class:
public class WebDataContextProvider : DataContextProvider
{
private const string Key = "WebDataContextProvider.DataContext";
public override DataContext GetCurrent()
{
return (DataContext)HttpContext.Current.Items[Key];
}
public override void OpenNew()
{
HttpContext.Current.Items[Key] = new DataContext();
}
}
And in your global.asax:
You add a field of type WebDataContextProvider:
WebDataContextProvider dataContextProvider = new WebDataContextProvider();
You override the application start event for doing:
DataContext.Provider = dataContextProvider;
In your Request Begin event you put:
dataContextProvider.OpenNew();
And in your Request End event you put:
dataContextProvider.CloseCurrent();
For test
For your test projects you can follow the same logic, but creating a TestDataContextProvider, like:
public class WebDataContextProvider : DataContextProvider
{
[ThreadStatic]
private static DataContext Current;
public override DataContext GetCurrent()
{
return Current;
}
public override void OpenNew()
{
Current = new DataContext();
}
}
And in your open and close the data context in your SetUp and TearDown methods, and configuring the "current provider" in the constructor of the Test or the TestFixtureSetUp
Hope it helps.

How to create meaningful unit tests for fakes

I understand the basics on how to unit test, however I often struggle at finding what meaningful things to test. I believe I have to create a fake implementation and inject into the consumer. I have a service class responsible to subscribing to (using Exchange Web Services (EWS)) Exchange 2010 requesting updates on new mail. In order to decouple my subscribing implementation from the service itself I decided to inject the implementation in the service. Below is what I currently have. I've omitted code dealing specifically communicating with Exchange.
// Not a big fan of having two identical interfaces...
public interface IStreamingNotificationService
{
void Subscribe();
}
public interface IExchangeService
{
void Subscribe();
}
public class StreamingNotificationService : IStreamingNotificationService
{
private readonly IExchangeService _exchangeService;
public StreamingNotificationService(IExchangeService exchangeService)
{
if (exchangeService == null)
{
throw new ArgumentNullException("exchangeService");
}
_exchangeService = exchangeService;
}
public void Subscribe()
{
_exchangeService.Subscribe();
}
}
public class ExchangeServiceImpl : IExchangeService
{
private readonly INetworkConfiguration _networkConfiguration;
private ExchangeService ExchangeService { get; set; }
public ExchangeServiceImpl(INetworkConfiguration networkConfiguration)
{
if (networkConfiguration == null)
{
throw new ArgumentNullException("networkConfiguration");
}
_networkConfiguration = networkConfiguration;
// Set up EWS
}
public void Subscribe()
{
// Subscribe for new mail notifications.
}
}
More specifically, how do I create a meaningful unit test to ensure subscribing works the way it should?
Usually you would use a mocking framework to create a fake exchange and test on this object that Subscribe was indeed called. I usually use Rhino Mocks, and your test would look e.g. like this (there are many ways to implement it):
[Test]
public void SubscribesToExchange()
{
var exchange = MockRepository.GenerateMock<IExchangeService>(); //this is the stub
var service = StreamingNotificationService(exchange); //this is the object we are testing
service.Subscribe();
service.AssertWasCalled(x => x.Subscribe(););
}
Decoupling and injection is always a very good idea in terms of unittesting.
Now you can easily test your StreamingNotificationService class. All you have to do is to test is if construction behaves nice, and if subscribemethod calls your injected (and fake) IExchangeService.

Categories