Sorted By: Tag (unit-testing)

Autofac and ASP.NET Web API System.Web.Http.Services.IDependencyResolver Integration

In this post, you can make Autofac work with ASP.NET Web API System.Web.Http.Services.IDependencyResolver. Solution to the 'controller has no parameterless public constructor' error.
2012-02-27 07:43
Tugberk Ugurlu


I have been using Ninject in all of my ASP.NET MVC applications till Chris Marisic (@dotnetchris) poked me on twitter about how slow Ninject is. After a little bit of research, I changed it to Autofac which works pretty perfectly.

ASP.NET Web API has nearly the same Dependency Injection support as ASP.NET MVC. As we do not have a built in support for ASP.NET Web API in Autofac (yet), I created a simple one. The implementation is not as straight forward as Ninject and you probably saw the below error if you tried to make it work:

System.InvalidOperationException:

An error occurred when trying to create a controller of type 'TourismDictionary.APIs.Controllers.WordsController'. Make sure that the controller has a parameterless public constructor.

Let’s see how it works:

First I created a class which implements System.Web.Http.Services.IDependencyResolver interface.

internal class AutofacWebAPIDependencyResolver : 
    System.Web.Http.Services.IDependencyResolver {

    private readonly IContainer _container;

    public AutofacWebAPIDependencyResolver(IContainer container) {

        _container = container;
    }

    public object GetService(Type serviceType) {

        return 
            _container.IsRegistered(serviceType) ? 
            _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType) {

        Type enumerableServiceType = 
            typeof(IEnumerable<>).MakeGenericType(serviceType);
            
        object instance = 
            _container.Resolve(enumerableServiceType);
            
        return ((IEnumerable)instance).Cast<object>();
    }
}

And I have another class which holds my registrations and sets the ServiceResolver with GlobalConfiguration.Configuration.ServiceResolver.SetResolver method which is equivalent to DependencyResolver.SetResolver method:

internal class AutofacWebAPI {

    public static void Initialize() {
        var builder = new ContainerBuilder();
        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            new AutofacWebAPIDependencyResolver(RegisterServices(builder))
        );
    }

    private static IContainer RegisterServices(ContainerBuilder builder) {

        builder.RegisterAssemblyTypes(
            typeof(MvcApplication).Assembly
        ).PropertiesAutowired();

        //deal with your dependencies here
        builder.RegisterType<WordRepository>().As<IWordRepository>();
        builder.RegisterType<MeaningRepository>().As<IMeaningRepository>();

        return
            builder.Build();
    }
}

Then, initialize it at Application_Start:

public class MvcApplication : System.Web.HttpApplication {

    private void Configure(HttpConfiguration httpConfiguration) {

        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

    protected void Application_Start() {

        Configure(GlobalConfiguration.Configuration);
        AutofacWebAPI.Initialize();
    }

}

There are different ways of doing it but I like this approach.

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: PM> Install-Package GenericRepository.EF
2012-01-15 08:41
Tugberk Ugurlu


Couple of weeks ago, I have done two blog post on Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle and How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking and I have put up the https://github.com/tugberkugurlu/GenericRepoWebApp up on GitHub as well.

Now, the Generic Repository implementation has its own project separately: https://github.com/tugberkugurlu/GenericRepository. This is a simple project and has not much inside it but it is nice to have something static so that it can be improved along the way.

Here is a brief intro:

This little project contains a Generic Repository infrastructure for .NET applications and also a DbContext Implementation of that.

You can find more information about the main idea of this pattern and the usage on ASP.NET MVC along with Unit Testing by visiting the below links:

How to Install

You can directly install this little project from Nuget. There are two packages:

GenericRepository

image

Generic Repository Infrastructure For .NET Applications

GenericRepository.EF

image

Generic Repository DbContext Implementation

Releases

Under the master branch, you can find the latest stable release of this project.

Also, you can see the most up-to-date project under develop branch. Repository under develop branch is possibly the unstable version of the project.

You can also find all the releases under Tags section.

I await for your PRs :)

How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking

In this blog post we will see how to work with generic repositories on ASP.NET MVC and unit testing them by mocking with moq
2011-12-22 17:05
Tugberk Ugurlu


image

I have blogged about Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle but that blog post only contains how we can implement that pattern on our DAL (Data Access Layer) project. Now, let’s see how it fits into our ASP.NET MVC application.

I created a sample project which basically has CRUD operations for Foo class and I put the complete code of the project on GitHub. https://github.com/tugberkugurlu/GenericRepoWebApp

So, in the previous blog post we have created our DAL project and repository classes based on our generic repository. I have created an ASP.NET MVC 3 Web Application project and a Visual Studio Test Project besides the DAL project. On the left had side, you can see how the project structure looks like inside solution explorer.

When we think about the project, we have repository classes which implements GenericRepositroy<C, T> abstract class and individual repository interfaces. So, we need a way to inject our concrete repository classes into our ASP.NET MVC application so that we make our application loosely coupled which means unit testing friendly.

Fortunately, ASP.NET MVC has been built with unit testing in mind so it makes dependency injection very easy with DependencyResolver class. DependencyResolver class Provides a registration point for dependency resolvers that implement IDependencyResolver or the Common Service Locator IServiceLocator interface. But we won’t be dealing with that class at all. Instead, we will use a third party dependency injector called Ninject. Ninject also has a package which benefits from DependencyResolver of ASP.NET MVC. We will use Nuget to bring down Ninject.

image

After we install the package, we will see a folder named App_Start added to our project. Inside that folder, open up the NinjectMVC3.cs file and go to RegisterServices method. In our case, here what we do:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel) {

    kernel.Bind<IFooRepository>().To<FooRepository>();
    kernel.Bind<IBarRepository>().To<BarReposiltory>();
}

This does some stuff behind the scenes and I won’t go into details here but I really recommend you to go and take a look at series of blog posts which Brad Wilson has done on ASP.NET MVC 3 Service Location. However, if we try to explain it with simplest words, Ninject news up the controller classes with parameters which we specify. In this case, if a controller constructor accepts a parameter which is type of IFooRepository, Ninject will give it FooRepository class and news it up. We will see why this is useful on unit testing stage.

When we look inside the RegisterServices method, we don’t see neither GenericRepository nor IGenericRepository because the way we implement them enables them to work behind the scenes.

As for the implementation, here how the controller looks like:

public class FooController : Controller {

    private readonly IFooRepository _fooRepo;
    
    public FooController(IFooRepository fooRepo) {
        _fooRepo = fooRepo;
    }

    public ViewResult Index() {

        var model = _fooRepo.GetAll();
        return View(model);
    }

    public ActionResult Details(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    public ActionResult Edit(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    [ActionName("Edit"), HttpPost]
    public ActionResult Edit_post(Foo foo) {

        if (ModelState.IsValid) {

            try {
                _fooRepo.Edit(foo);
                _fooRepo.Save();

                return RedirectToAction("details", new { id = foo.FooId });

            } catch (Exception ex) {
                ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
            }
        }

        //If we come here, something went wrong. Return it back.
        return View(foo);
    }

    public ActionResult Create() {

        return View();
    }

    [ActionName("Create"), HttpPost]
    public ActionResult Create_post(Foo foo) {

        if (ModelState.IsValid) {

            try {
                _fooRepo.Add(foo);
                _fooRepo.Save();

                return RedirectToAction("details", new { id = foo.FooId });

            } catch (Exception ex) {
                ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
            }
        }

        //If we come here, something went wrong. Return it back.
        return View(foo);

    }

    public ActionResult Delete(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    [ActionName("Delete"), HttpPost]
    public ActionResult Delete_post(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        _fooRepo.Delete(model);
        _fooRepo.Save();

        return RedirectToAction("Index");
    }
}

All of the action methods do some very basic stuff but one thing to notice here is the below code:

    private readonly IFooRepository _fooRepo;
    
    public FooController(IFooRepository fooRepo) {
        _fooRepo = fooRepo;
    }

As I mentioned before, controller constructor accepts a parameter which is type of IFooRepository and inside the constructor method, we expose the parameter for internal use of that controller class.

I have some views which corresponds to each action method and they work as expected.

Unit Testing

So, how do we unit test that controller without connecting to our database? When we think theoretically, what we need is a fake repository which implements IFooRepository interface so that we can pass that fake repository into our controller as a constructor parameter. Pay attention here that we still has no need for neither generic repository interface nor generic repository abstract class. We just need to fake FooRepository interface with fake data.

We will do this by mocking and creating mock objects. In order to do that, we will benefit from an awesome library called Moq.

As you can see inside the project on GitHub, I didn’t use NuGet to bring down the Moq because I tried and it failed over and over again. So, I put that inside the lib folder under the root directory and reference it from there.

After you reference the Moq library inside the Test application, create a class named FooControllerTest.cs. Here how it should look like at first:

[TestClass]
public class FooControllerTest {

}

So empty. We will start to fill it in with a mock of IFooReporsitory. Below, you can see the complete code which enables that:

[TestClass]
public class FooControllerTest {

    private IFooRepository fooRepo;

    [TestInitialize]
    public void Initialize() {

        //Mock repository creation
        Mock<IFooRepository> mock = new Mock<IFooRepository>();
        mock.Setup(m => m.GetAll()).Returns(new[] { 
            new Foo { FooId = 1, FooName = "Fake Foo 1" },
            new Foo { FooId = 2, FooName = "Fake Foo 2" },
            new Foo { FooId = 3, FooName = "Fake Foo 3" },
            new Foo { FooId = 4, FooName = "Fake Foo 4" }
        }.AsQueryable());

        mock.Setup(m => 
            m.GetSingle(
                It.Is<int>(i => 
                    i == 1 || i == 2 || i == 3 || i == 4
                )
            )
        ).Returns<int>(r => new Foo { 
            FooId = r,
            FooName = string.Format("Fake Foo {0}", r)
        });

        fooRepo = mock.Object;
    }

}

This Initialize method will run before all of the test methods run so we can work inside that method in order to mock our object.

In here, first I have setup a mock for GetAll method result and it returns 4 instances or Foo class.

Second, I do the same thing for GetSingle method. It looks a little different because it accepts a parameter type of int. What I am telling there is that: there are 4 instances I have here and if the parameter matches one of those instances, it will returns a Foo class which is a type of GetSingle method returns.

Lastly, I expose the mock object for internal use for the test class.

Now we have an IFooRepository instance we can work with. We have completed the hard part and now we can start writing our unit tests. Here is some of possible unit tests that we can have:

[TestClass]
public class FooControllerTest {

    private IFooRepository fooRepo;

    [TestInitialize]
    public void Initialize() {

        //Mock repository creation
        Mock<IFooRepository> mock = new Mock<IFooRepository>();
        mock.Setup(m => m.GetAll()).Returns(new[] { 
            new Foo { FooId = 1, FooName = "Fake Foo 1" },
            new Foo { FooId = 2, FooName = "Fake Foo 2" },
            new Foo { FooId = 3, FooName = "Fake Foo 3" },
            new Foo { FooId = 4, FooName = "Fake Foo 4" }
        }.AsQueryable());

        mock.Setup(m => 
            m.GetSingle(
                It.Is<int>(i => 
                    i == 1 || i == 2 || i == 3 || i == 4
                )
            )
        ).Returns<int>(r => new Foo { 
            FooId = r,
            FooName = string.Format("Fake Foo {0}", r)
        });

        fooRepo = mock.Object;
    }

    [TestMethod]
    public void is_index_returns_model_type_of_iqueryable_foo() {
        
        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var indexModel = fooController.Index().Model;

        //Assert
        Assert.IsInstanceOfType(indexModel, typeof(IQueryable<Foo>));
    }

    [TestMethod]
    public void is_index_returns_iqueryable_foo_count_of_4() {

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var indexModel = (IQueryable<object>)fooController.Index().Model;

        //Assert
        Assert.AreEqual<int>(4, indexModel.Count());
    }

    [TestMethod]
    public void is_details_returns_type_of_ViewResult() {

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var detailsResult = fooController.Details(1);

        //Assert
        Assert.IsInstanceOfType(detailsResult, typeof(ViewResult));
    }

    [TestMethod]
    public void is_details_returns_type_of_HttpNotFoundResult() { 

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var detailsResult = fooController.Details(5);

        //Assert
        Assert.IsInstanceOfType(detailsResult, typeof(HttpNotFoundResult));
    }
}

When I run the all the test, I should see all of them pass and I do:

image

I hope this blog post gives you an idea. Stay tuned for others Winking smile

NOTE:

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: http://www.tugberkugurlu.com/archive/entity-framework-dbcontext-generic-repository-implementation-is-now-on-nuget-and-github

Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle

We will see how we can implement Generic Repository Pattern with Entity Framework and how to benefit from that.
2011-12-22 09:07
Tugberk Ugurlu


IMPORTANT NOTE:

I have a new blog post about Generic Repository implementation for Entity Framework. Please check it out instead of this one: Clean, Better, and Sexier Generic Repository Implementation for Entity Framework

NOTE:

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: http://www.tugberkugurlu.com/archive/entity-framework-dbcontext-generic-repository-implementation-is-now-on-nuget-and-github

DRY: Don’t repeat yourself which is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. That’s what Wikipedia says. In my words, if you are writing the same code twice, follow these steps:

  • Step back.
  • Sit.
  • Think about it and dwell on that.

That’s what I have done for repository classes on my DAL projects. I nearly all the time use Entity Framework to reach out my database and I create repositories in order to query and manipulate data inside that database. There are some specific methods which I use for every single repository. As you can assume, those are FindBy, Add, Edit, Delete, Save. Let’s see on code what is my story here.

First approach (worst approach)

At first, long time ago, I have been creating all the single methods for each interface. For example below one is one of my repository interfaces:

I am giving the examples here with EF 4.2 but I was following this approach with EF 4 which does not contain DbContext class.

public interface IFooRepository {
        
    IQueryable<Foo> GetAll();
    Foo GetSingle(int fooId);
    IQueryable<Foo> FindBy(Expression<Func<Foo, bool>> predicate);
    void Add(Foo entity);
    void Delete(Foo entity);
    void Edit(Foo entity);
    void Save();
}

This repo is for Foo class I have (imaginary). Let's see the implementation for Bar class.

public interface IBarRepository {
    
    IQueryable<Bar> GetAll();
    Bar GetSingle(int barId);
    IQueryable<Bar> FindBy(Expression<Func<Bar, bool>> predicate);
    void Add(Bar entity);
    void Delete(Bar entity);
    void Edit(Bar entity);
    void Save();
}

Implementation nearly exactly the same here. Here is also an example of implementing one of these interfaces:

public class FooRepository : IFooRepository {

    private readonly FooBarEntities context = new FooBarEntities();

    public IQueryable<Foo> GetAll() {

        IQueryable<Foo> query = context.Foos;
        return query;
    }

    public Foo GetSingle(int fooId) {

        var query = this.GetAll().FirstOrDefault(x => x.FooId == fooId);
        return query;
    }

    public void Add(Foo entity) {

        context.Foos.Add(entity);
    }

    public void Delete(Foo entity) {

        context.Foos.Remove(entity);
    }

    public void Edit(Foo entity) {

        context.Entry<Foo>(entity).State = System.Data.EntityState.Modified;
    }

    public void Save() {

        context.SaveChanges();
    }
}

Also imagine this implementation for BarRepository as well. Indeed, there would be probably more repository classes for your project. After playing like that for a while I decided to do something different which still sucked but better.

A better approach but still sucks

I created a generic interface which saves me a lot of keystrokes. Here how it looks like:

public interface IGenericRepository<T> where T : class {
    
    IQueryable<T> GetAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    void Add(T entity);
    void Delete(T entity);
    void Edit(T entity);
    void Save();
}

And how I implemented in on repository interfaces:

public interface IFooRepository : IGenericRepository<Foo> {
    
    Foo GetSingle(int fooId);
}
public interface IBarRepository : IGenericRepository<Bar> {
    
    Bar GetSingle(int barId);
}

You can see that I only needed to implement GetSingle method here and others come with IGenericRepositoy<T> interface.

Where I implement these repository interfaces to my concrete classes, I still need to go over all the methods and create them individually. The repository class looked like as the same. So it leads me to a final solution which is the best one I can come up with so far.

Best approach

The generic interface I have created is still legitimate and usable here. In fact, I won’t touch the repository interfaces at all. What I did here first is to create an abstract class which implements IGenericReposity<T> interface but also accepts another type parameter defined in a generic declaration which is a type of DbConetxt class. Here is how it looks like:

public abstract class GenericRepository<C, T> : 
    IGenericRepository<T> where T : class where C : DbContext, new() {

    private C _entities = new C();
    public C Context {

        get { return _entities; }
        set { _entities = value; }
    }

    public virtual IQueryable<T> GetAll() {

        IQueryable<T> query = _entities.Set<T>();
        return query;
    }

    public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) {

        IQueryable<T> query = _entities.Set<T>().Where(predicate);
        return query;
    }

    public virtual void Add(T entity) {
        _entities.Set<T>().Add(entity);
    }

    public virtual void Delete(T entity) {
        _entities.Set<T>().Remove(entity);
    }

    public virtual void Edit(T entity) {
        _entities.Entry(entity).State = System.Data.EntityState.Modified;
    }

    public virtual void Save() {
        _entities.SaveChanges();
    }
}

This is so nice because of some factors I like:

  • This implements so basic and ordinary methods
  • If necessary, those methods can be overridden because each method is virtual.
  • As we newed up the DbContext class here and expose it public with a public property, we have flexibility of extend the individual repositories for our needs.
  • As we only implement this abstract class only to our repository classes, it won’t effect unit testing at all. DbContext is not in the picture in terms of unit testing.

So, when we need to implement these changes to our concrete repository classes, we will end up with following result:

public class FooRepository :
    GenericRepository<FooBarEntities, Foo>, IFooRepository {

    public Foo GetSingle(int fooId) {

        var query = GetAll().FirstOrDefault(x => x.FooId == fooId);
        return query;
    }
}
public class BarReposiltory : 
    GenericRepository<FooBarEntities, Bar>, IBarRepository  {

    public Bar GetSingle(int barId) {

        var query = Context.Bars.FirstOrDefault(x => x.BarId == barId);
        return query;
    }
}

Very nice and clean. Inside BarRepository GetSingle method, as you see I use Context property of GenericRepository<C, T> abstract class to access an instance of DbContext.

So, how the things work inside our ASP.NET MVC project? this is another story but no so complicated. I will continue right from here on my next post.

UPDATE:

Here is the next post:

How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking

Unit Testing With xUnit.net for ASP.NET MVC Web Applications - Part 1

In this blog post, we will see how we set up our environment for xUnit.net Unit Testing Framework. This is the first blog post of the blog post series on Unit Testing With xUnit.net for ASP.NET MVC.
2011-10-16 14:40
Tugberk Ugurlu


you-need-some-tests-yo...

I have been developing web applications with ASP.NET MVC for long time and to be honest, none of them has good Unit Testing backing them up. I don’t know you have realized but I am not even mentioning anything about TDD (Test Driven Development).

This isn’t a big problem for me. It is mainly because I work in a team, which has only one member inside it [yeah, it’s me :)], for my company. But all the cool guys are always talking about how awesome it is to work with Unit Testing.

This made me obsessed about Unit Testing and I stated to spend real quality time on investigating that so that I will be able to sleep without having dreams about a guy who wears an ugly sunglasses and telling me ‘You need some tests yo!’. (No, I am just kidding, I am not insane. At least, not yet.)

Visual Studio has a built-in test environment but I figured that is not enough. So, from now on, I will be using xUnit.net for my unit test applications.

What is xUnit.net?

xUnit.net is a unit testing tool for the .NET Framework. Written by the original inventor of NUnit, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other .NET languages. Works with ReSharper, CodeRush, and TestDriven.NET.

Set Up Your Environment

First thing is first. Go to http://xunit.codeplex.com/releases/view/62840 to download the latest version of xUnit.net. At the time that I write this blog post, the latest version of xUnit.net is 1.8. Unzip the file inside a path and run the xUnit.installer.exe file.

You will have a window opened in front of you. For the sake of simplicity, I only check Microsoft ASP.NET MVC 3 Unit Testing Templates and click Apply button. After that, here is the screen shots of the result :

imageimage

File > New > Project

After the installation, go to VS 2010 and follow File > New > Project > ASP.NET MVC 3 Web Application. You will see that xUnit is sitting right there.

image

imageGo ahead and create the project. When you create the project you will see the usual HomeController.cs inside your Controllers folder. With xUnit.net project, you will see that we get HomeControllerFacts.cs file out of the box as sample. This file gives us a head start on this new thing for us.

On this blog post, I would like to focus on how things goes for us instead of how we write our unit test code.

As we have seen, we get a sample project and sample test project with some tests written inside it the the sample application. When we build the solution, we should be able to process successfully.

So, the next question is how we run our tests. The xUnit.net framework supports 4 distinct test runners:

  • GUI Test Runner
  • Console Test Runner
  • TestDriven.NET Test Runner
  • Resharper 4.0 Test Runner

I will walk you through how we run our tests with GUI Test Runner for this blog post.

Running xUnit Tests With GUI Test Runner

Navigate to the path which you have installed you xUnit project files and you will notice 4 files there which are green as follows :

image

Firstly, they are not same. I am sure you already understood what is for what but here is the detailed info :

xuit.gui.clr4, xuit.gui.clr4.x86 : This is for CLR 4 projects. .x86 is for x86 compatibility which you already know.

xuit.gui, xuit.gui.x86 : This is for CLR 2 projects. .x86 is for x86 compatibility which you already know.

I have open up the xuit.gui.exe which is suitable for me. Then, from the GUI, select the menu option Assembly > Open (Ctrl + O for keyboard shortcut) and select your test application output dll file (Be careful here. If you don’t build your solution before this process, you won’t be able to find the output dll file).

image

When you make the selection, the runner will be able to pick up all the tests as you can see below :

image

Let’s touch the Run All button on the left side at the bottom :

image

Looks cool. I break one of the tests on purpose so that we can see it failing :

image

So, this is the simplest as it can get. This blog post is supposed to be the first blog post of the blog post series on Unit Testing With xUnit.net for ASP.NET MVC and I will be blogging on further features of xUnit for ASP.NET MVC. Stay tuned!

Tags