mocking in unit tests with dependency injection - c#

I am wondering about the best way to make my system testable.
I am unsure of the best practice with DI and mocking.
If DI is facilitated by using interfaces should i build mock classes which implement the same interface as the real classes?
And then use these mock classes in my tests via DI?
I importing data into HDInsight. The data is taken from azure queues.
I want to mock/emulate both the queue and the hdinsight so my unit tests are fast and decoupled.
Should i use dependency injection in my tests or is moq sufficient, are these supposed to operate independently?

Mocks and Dependency Injection go hand in hand because without dependency injection, you would not be able to have your classes use the mocks instead of the real thing. What you don't need is a Dependency Injection Container (like Ninject for example). You can use it if you like, but if you did it right, you should be able to Unit-Test your classes by supplying all dependencies yourself.

Moq is sufficient.
Your tests use the mocks to help facilitate results. They are quick and easy to setup (once you are used to whatever mocking library you choose).
If you were to utilize a DI framework.. you would be tripling your workload. Not only are you manually stubbing out mocks.. but you are also then maintaining your DI configuration for your tests. This simply wouldn't fit nicely into any workflow.

Related

Difference between unity container and unit of work (MVC)

What is the difference between unity container and unit of work(if there is any), as I understand both are doing same thing, but how to determine which one to use.
I need to be sure, that I understand it well and there is no any difference.
Unity is an inversion of control container, where inversion of control is a design pattern, and unit of work is another design pattern...
The main difference between the two is they're absolutely different design patterns, there's no criteria to match both patterns and find out similarities.
OP said...
I didn't know about inversion of control, read that link and have done
some search, but still both are related with dependency injection and
no one uses combination of them(both of it), they are using just one
of them
Dependency injection is an approach to inversion of control.
In the other hand, unit of work has nothing to do with inversion of control or dependency injection. Again, unit of work and inversion of control/dependency injection are different design patterns.
Perhaps you can inject dependencies in an unit of work, or inject an unit of work somewhere to decouple your architecture from the concrete implementation of the so-called unit of work. There's a big difference from comparing two design patterns from just understanding that design patterns can cooperate to build a software stack.
Your Ioc container, unity, may or may not contain a hard implementation at the other end that is using unit of work. You will implement your interfaces using some specific class that satisfies your generic interface definitions but using a specific backing store such as Entity Framework, LinqToSql, Ado Sql Commands, test stubs, etc.. Unit of work would not be applicable if you are using Ado sql commands so it is usually a good idea to only include generic functionality in your ioc "service contracts".

Simple Injector Unit testing [duplicate]

How can a IoC Container be used for unit testing? Is it useful to manage mocks in a huge solution (50+ projects) using IoC? Any experiences? Any C# libraries that work well for using it in unit tests?
Generally speaking, a DI Container should not be necessary for unit testing because unit testing is all about separating responsibilities.
Consider a class that uses Constructor Injection
public MyClass(IMyDependency dep) { }
In your entire application, it may be that there's a huge dependency graph hidden behind IMyDependency, but in a unit test, you flatten it all down to a single Test Double.
You can use dynamic mocks like Moq or RhinoMocks to generate the Test Double, but it is not required.
var dep = new Mock<IMyDependency>().Object;
var sut = new MyClass(dep);
In some cases, an auto-mocking container can be nice to have, but you don't need to use the same DI Container that the production application uses.
I often use an IoC container in my tests. Granted, they are not "unit tests" in the pure sense. IMO They are more BDDish and facilitate refactoring. Tests are there to give you confidence to refactor. Poorly written tests can be like pouring cement into your code.
Consider the following:
[TestFixture]
public class ImageGalleryFixture : ContainerWiredFixture
{
[Test]
public void Should_save_image()
{
container.ConfigureMockFor<IFileRepository>()
.Setup(r => r.Create(It.IsAny<IFile>()))
.Verifiable();
AddToGallery(new RequestWithRealFile());
container.VerifyMockFor<IFileRepository>();
}
private void AddToGallery(AddBusinessImage request)
{
container.Resolve<BusinessPublisher>().Consume(request);
}
}
There are several things that happen when adding an image to the gallery. The image is resized, a thumbnail is generated, and the files are stored on AmazonS3. By using a container I can more easily isolate just the behavior I want to test, which in this case is the persisting part.
An auto-mocking container extension comes in handy when using this technique:
http://www.agileatwork.com/auto-mocking-unity-container-extension/
How can a Ioc Container be used for unit testing?
IoC will enforce programming paradigms that will make unit testing in isolation (i.e. using mocks) easier: use of interfaces, no new(), no singletons...
But using the IoC container for testing is not really a requirement, it will just provide some facilities e.g. injection of mocks but you could do it manually.
Is it useful to manage mocks in a huge solution (50+ projects) using IoC?
I'm not sure what you mean by managing mocks using IoC. Anyway, IoC containers can usually do more than just injecting mocks when it comes to testing. And if you have decent IDE support that makes refactoring possible, why not using it?
Any experience?
Yes, on a huge solution, you need more than ever a non error-prone and refactoring-adverse solution (i.e. either through a type safe IoC container or good IDE support).
Using containers with ability to resolve unregistered/uknown services like SimpleInjector, DryIoc (its mine) can return mocks for not yet implemented interfaces.
Which means that you can start development with first simple implementation and its mocked dependencies, and replace them with real thing as you progress.

Unit Testing in CSLA? How? What?

Does anyone have an example of unit testing in CSLA. I find it difficult to implement TDD with this framework and was wondering if there is any simple ways of doing this. Is there any other Mock Framework I could use besides TypeMock Isolator that is for free to build my test object? Please if you have any suggestions and samples/examples, I would be delighted? Thank you.
I'm not sure if I'm telling you some new information, but from CSLA 4 it's easier to unit test your custom BusinessRules and if you are using repositories as your data layer, you can mock the repositories to test the business objects together with the front end using them. Just remember that business objects aren't much more then a bunch of objects with properties where you should use Business Rules to implement business logic. Those Business Rules are just classes you can unit test without a problem.
It all depends on how your infrastructure is. Are you using a IoC pattern?
Which version of CSLA are you using?
Are you using the CSLA ObjectFactory's?
If you use CSLA as it should be used you'll have static factory methods and you have a non-public constructor. If you still want to unit test those properties inside the BusinessObjects you can choose out of some options.
If you use IoC for the datalayer (repositories) then you can mock those and test the business objects by configuring the IoC with mocks and stubs and in the testmethod call the factory methods and do your test.
If you don't use IoC, you might be lucky if you went for the CSLA ObjectFactory solution--there you can use mocks and stubs.
If you don't use IoC and didn't go for the ObjectFactory, you can't unit test the business objects that easily. But it's still possible by registering a custom DataPortal. Inside the DataPortal you can use reflection to construct the business object and resolve some mock/stub for that specific business object. It's not easy, but it's doable.
Sorry that I don't have any examples.

Unit testing the repository. NHibernate

I've got NHibernate-based (constructor ISessionFactory injection) generic repository implementation which is stored inside DAL. It implements contract which is stored in `Domain Layer'.
Should I test real repository behavior using SQl CE or should I refactor my application to support agnostic-like (like in Tim Maccharty's book http://www.wrox.com/WileyCDA/WroxTitle/productCd-0470147563,descCd-authorInfo.html) Unit of Work and then give my fake implementation of IUnitOfWorkRepository?
Is it a valid approach to run tests on a local database exposing real repository implementation?
Thanks!
The issue is what your are testing and why. That will answer the question.
If:
I want to test a third party tool
That is, are you testing if NHibernate is working (not a kind of test
I do). Then do whatever it requires, so refactoring not required. Loose yourself.
I want to test how my code interacts with a thrid party tool
Then you are talking about what I like to call a interaction test. Refactoring is required as your more interested in how your using NHiberate than if it works.
I want to test my code
The abstract NHibernate entirely. Do whatever is necessary ... wrapper? Your now back into unit testing.
I want to test my application from a user point of view
I think this is above the scope your talking. But you can use this scope talking about components. So ... hmmm ... worthwhile but not easy. Not a unit test, so you want to instantiate the component/app and run the whole thing as its 'user' does. I call these 'UATs' and usually implement as 'Coded UATs'.
A unit test is testing a unit in isolation. So, no, it's not even a unit test if you're going to the database.
Abstract away and test your repositories with mocked up interfaces.
I think to test the repositories you need to use the actual scenario. Otherwise you don't have any other place to test the database access. Mocking the repositories is not a good practice. Because you don't have any logic which is need to test in the repositories. I think you need to write integration tests which is calling actual repositories to have any benefit from it.

What should be the strategy of unit testing when using IoC?

After all what I have read about Dependency Injection and IoC I have decided to try to use Windsor Container within our application (it's a 50K LOC multi-layer web app, so I hope it's not an overkill there). I have used a simple static class for wrapping the container and I initialize it when starting the app, which works quite fine for now.
My question is about unit testing. I know that DI is going to make my life much easier there by giving me the possibility of injecting stub / mock implementations of class collaborators to the class under test. I have already written a couple of tests using this technique and it seems to make sense for me. What I am not sure about is whether I should be using IoC (in this case Windsor Castle) also in unit tests (probably somehow configure it to return stubs / mocks for my special cases) or is it better to wire-up all the dependencies manually in the tests. What do you think and what practice has worked for you ?
You don't need DI container in unit tests because dependencies are provided through mock objects generated with frameworks such as Rhino Mocks or Moq. So for example when you are testing a class that has a dependency on some interface this dependency is usually provided through constructor injection.
public class SomeClassToTest
{
private readonly ISomeDependentObject _dep;
public SomeClassToTest(ISomeDependentObject dep)
{
_dep = dep;
}
public int SomeMethodToTest()
{
return _dep.Method1() + _dep.Method2();
}
}
In your application you will use a DI framework to pass some real implementation of ISomeDependentObject in the constructor which could itself have dependencies on other objects while in a unit test you create a mock object because you only want to test this class in isolation. Example with Rhino Mocks:
[TestMethod]
public void SomeClassToTest_SomeMethodToTest()
{
// arrange
var depStub = MockRepository.CreateStub<ISomeDependentObject>();
var sut = new SomeClassToTest(depStub);
depStub.Stub(x => x.Method1()).Return(1);
depStub.Stub(x => x.Method2()).Return(2);
// act
var actual = sut.SomeMethodToTest();
// assert
Assert.AreEqual(3, actual);
}
I'm working on an ASP.NET MVC project with about 400 unit tests. I am using Ninject for dependency injection and MBUnit for testing.
Ninject is not really necessary for unit testing, but it reduces the amount of code I have to type. I only have to specify once (per project) how my interfaces should be instantiated as opposed to doing this every time I initialize the class being tested.
In order to save time on writing new tests, I have created test fixture base classes with as much generic setup code as possible. The setup procedures in those classes intialize fake repositories, create some test data and a fake identity for the test user. Unit tests only initialize data that is too specific to go into generic setup procedures.
I am also mocking objects (as opposed to faking) in some tests, but I found that faking data repositories results in less work and more accurate tests.
For example, it would be more difficult to check if the method under test I properly commits all updates to the repository after making them when using a repository mock than when I am using a repository fake.
It was quite a bit of work to set up at the beginning, but really helped me reduce save a lot of time in the long run.
I've just written a very similar style and size app. I wouldn't put any dependency injection in the unit tests because it is not complicated enough to be necessary. You should use a mocking framework to create your mocks (RhinoMocks / Moq).
Also Automocking in Moq or the Auto Mock Container in Rhinomocks will simplify building your mocks further.
Auto mocking allows you to get object
of the type you want to test without
setting up mocks by hand. All
dependencies are mocked automatically
(assuming they are interfaces) and
injected into the type constructor. If
you need to you can set up expected
behavior, but you don't have to.
As Darin has already pointed out, you don't need to use DI if you have mocks. (However, DI has a few other benefits as well, including, first of all, lessening dependencies in your code, which makes your code much easier to maintain and extend in the long run.)
I personally prefer wiring up everything in my unit tests, thus relying as little as possible on external frameworks, config files etc.

Categories

Resources