ASP.NET MVC Unit Testing with Repository Pattern - asp.net-mvc

I am trying to get my feet wet with asp.net mvc3 and unit testing.
I have created a model which uses the repository pattern. Here's the interface:
public interface IExtensionRepository
{
IList<Extensions> ListAll();
}
Here's the repository:
public class ExtensionRepository : IExtensionRepository
{
private ExtensionsLSDataContext _dataContext;
public ExtensionRepository()
{
_dataContext = new ExtensionsLSDataContext();
}
public IList<Extensions> ListAll()
{
var extensions = from ext in _dataContext.Extensions
select ext;
return extensions.ToList();
}
}
Here's the controller:
public class ExtensionController : Controller
{
private IExtensionRepository _repository;
public ExtensionController()
: this(new ExtensionRepository())
{
}
public ExtensionController(IExtensionRepository repository)
{
_repository = repository;
}
}
The pages seem to function as designed. Things go astray with my unit test, however. It resides in another project in the same solution. I am using Moq and NUnit. Here's my test:
[Test]
public void Test_Extension_Index_Views()
{
Mock<Extensions> extension = new Mock<Extensions>();
List<Extensions> extList = new List<Extensions>();
extension.Object.Extension = "5307";
extension.Object.Extension_ID = 1;
extension.Object.ExtensionGroup_ID = 1;
extList.Add(extension.Object);
Mock<IExtensionRepository> repos = new Mock<IExtensionRepository>();
repos.Setup(er => er.ListAll()).Returns(extList);
var controller = new ExtensionController(repos);
var result = controller.Index() as ViewResult;
Assert.AreEqual("Index", result.ViewName);
}
I am getting the following errors for the line that begins "var controller...":
The best overloaded method match for
'MvcApplication1.Controllers.ExtensionController.ExtensionController(MvcApplication1.Models.IExtensionRepository)'
has some invalid arguments
And:
Argument 1: cannot convert from
'Moq.Mock'
to
'MvcApplication1.Models.IExtensionRepository'
I know I've missed the boat somewhere, but I haven't a clue as to where... any ideas?

Change this:
var controller = new ExtensionController(repos);
to this:
var controller = new ExtensionController(repos.Object);
PS.: I know it sucks, but that's the way Moq was designed.

Related

IdependencyResolver is always null in unit test using moq

I've implemented ninject in a mvc project and this works as expected now I'm wanting to unit test, but can't seem to get it to work:
controller:
private IDependencyResolver _resolver;
public HomeController(IDependencyResolver resolver)
{
_resolver = resolver;
}
public ActionResult Index()
{
var model = _resolver.GetService<ISignUpViewModel>();
return PartialView("Login", model);
}
Unit Test
private IDependencyResolver _resolverMock;
[TestMethod]
public void SignUpTest()
{
var ctrl = new HomeController(_resolverMock);
var signUpMock = new Mock<ISignUpViewModel>();
ctrl.Index();
ctrl.ViewData.Model = signUpMock;
//Assert.AreEqual("", "");
}
The resolver is always null.
Ive looked at Ninject.MockingKernel.Moq should I set the resolver in there?
Any idea where I'm going wrong?
Thanks
In the unit test you manually create HomeController instance, So you need mock IDependencyResolver. For example:
var resolverMock = new Mock<IDependencyResolver>();
var ctrl = new HomeController(resolverMock.Object);
....

unit test user.identity.getuserid asp.net mvc

I have a controller in which I am unit testing my Index action. I am having problem in unit testing User.Identity.GetUserId()
This is my controller
public ActionResult Index()
{
string userId = User.Identity.GetUserId();
DemoModel demoModel = _demoModelService.GetByUserId(userId);
MyModel myModel = new MyModel()
{
Name = demoModel.Name;
Description = demoModel.Description;
}
return View(myModel);
}
This is my Unit Test:
public void Test_Index_Action()
{
//Act
var result = controller.Index() as ViewResult;
//Assert
Assert.AreEqual("", result.ViewName);
}
When I debug my test method, as it reaches the first line of code(User.Identity.GetUserId) of my Index action, it generates null UserId. How can I access the userId in unit testing this code?
I've been struggeling with mvc unit test my self, while there are known techniques to improve testability of your mvc application, most of the projects I worked on are sadly not following them.
So I decided to start this project to help me and others who love to unit test their mvc application. Please take a look at: https://github.com/ibrahimbensalah/Xania.AspNet.Simulator.
Here is an example unit test class
using System.Web.Mvc;
using NUnit.Framework;
using Xania.AspNet.Simulator;
public class SimulatorTests
{
[Test]
public void ActionExecuteTest()
{
// arange
var controller = new TestController();
// act
var result = controller.Execute(c => c.Index());
// assert
Assert.AreEqual("Hello Simulator!", result.ViewBag.Title);
}
[Test]
public void UnAuthorizedActionTest()
{
// arrange
var controller = new TestController();
// act
var result = controller.Execute(c => c.UserProfile());
// assert
Assert.IsInstanceOf<HttpUnauthorizedResult>(result.ActionResult);
}
[Test]
public void AuthorizedActionTest()
{
// arrange
var controller = new TestController();
// act
var result = controller.Action(c => c.UserProfile()).Authenticate("user", null).Execute();
// assert
Assert.IsInstanceOf<ViewResult>(result.ActionResult);
}
}
public class TestController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Hello Simulator!";
return View();
}
[Authorize]
public ActionResult UserProfile()
{
return View();
}
}

Testing domain when using using repository pattern

I'm getting my feet wet with unit testing (TDD). I have a basic repository pattern I'm looking to test and I'm not really sure I'm doing things correctly. At this stage I'm testing my domain and not worrying about controllers and views. To keep it simple here is a demo project.
Class
public class Person
{
public int PersonID { get; set; }
public string Name{ get; set; }
}
Interface
public interface IPersonRepository
{
int Add(Person person);
}
Concrete
public class PersonnRepository : IPersonRepository
{
DBContext ctx = new DBContext();
public int Add(Person person)
{
// New entity
ctx.People.Add(person);
ctx.SaveChanges();
return person.id;
}
}
I've added NUnit and MOQ to my test project and want to know how to properly test the functionality.
I'm not sure it's right but after reading some blogs I ended up creating a FakeRepository, however if I test based on this, how is that validating my actual interface?
public class FakePersonRepository
{
Dictionary<int, Person> People = new Dictionary<int, Person>();
public int Add(Person person)
{
int id = People.Count + 1;
People.Add(id, person);
return id;
}
}
then tested with
[Test]
public void Creating_A_Person_Should_Return_The_ID ()
{
FakePersonRepository repository = new FakePersonRepository();
int id = repository.Add(new Person { Name = "Some Name" });
Assert.IsNotNull(id);
}
Am I anywhere close to testing in the correct manor?
I'd like to test things like not passing a name causes error etc in the future.
Am I anywhere close to testing in the correct manor?
I am afraid that you are not. The idea of having an interface is that it allows you to decouple other code that uses a repository such your controller and be able to unit test it in isolation. So let's suppose that you have the following controller that you want to unit test:
public class PersonController : Controller
{
private readonly IPersonRepository _repo;
public PersonController(IPersonRepository repo)
{
_repo = repo;
}
[HttpPost]
public ActionResult Create(Person p)
{
if (!ModelState.IsValid)
{
return View(p);
}
var id = _repo.Add(p);
return Json(new { id = id });
}
}
Notice how the controller doesn't depend on a specific repository implementation. All needs is that this repository implements the given contract. Now we could use a mocking framework such as Moq in the unit test to provide a fake repository and make it behave as we like in order to test the 2 possible paths in the Create action:
[TestMethod]
public void PersonsController_Create_Action_Should_Return_View_And_Not_Call_Repository_If_ModelState_Is_Invalid()
{
// arrange
var fakeRepo = new Mock<IPersonRepository>();
var sut = new PersonController(fakeRepo.Object);
var p = new Person();
sut.ModelState.AddModelError("Name", "The name cannot be empty");
fakeRepo.Setup(x => x.Add(p)).Throws(new Exception("Shouldn't be called."));
// act
var actual = sut.Create(p);
// assert
Assert.IsInstanceOfType(actual, typeof(ViewResult));
}
[TestMethod]
public void PersonsController_Create_Action_Call_Repository()
{
// arrange
var fakeRepo = new Mock<IPersonRepository>();
var sut = new PersonController(fakeRepo.Object);
var p = new Person();
fakeRepo.Setup(x => x.Add(p)).Returns(5).Verifiable();
// act
var actual = sut.Create(p);
// assert
Assert.IsInstanceOfType(actual, typeof(JsonResult));
var jsonResult = (JsonResult)actual;
var data = new RouteValueDictionary(jsonResult.Data);
Assert.AreEqual(5, data["id"]);
fakeRepo.Verify();
}
You need to make your DBContext injectable by extracting an interface for it:
public interface IDBContext{
IList<Person> People {get;} // I'm guessing at the types
void SaveChanges();
// etc.
}
Then inject that into your concrete class:
public class PersonRepository : IPersonRepository
{
IDBContext ctx;
public PersonRepository(IDBContext db) {
ctx = db;
}
public int Add(Person person)
{
// New entity
ctx.People.Add(person);
ctx.SaveChanges();
return person.id;
}
}
Your test would then look like:
[Test]
public void Creating_A_Person_Should_Return_The_ID ()
{
Mock<IDBContext> mockDbContext = new Mock<IDBContext>();
// Setup whatever mock values/callbacks you need
PersonRepository repository = new PersonRepository(mockDbContext.Object);
int id = repository.Add(new Person { Name = "Some Name" });
Assert.IsNotNull(id);
// verify that expected calls are made against your mock
mockDbContext.Verify( db => db.SaveChanges(), Times.Once());
//...
}
I'd personally look at writing an "integration test" for this, i.e. one that hits a real (ish) database as your data access layer should not contain any logic which makes testing in isolation worthwhile.
In this case you will require a database up and running. This could be a developer database already set up somewhere, or an in-memory database started as part of the tests arrange.
The reason for this is that I find (pure) unit tests of the DAL generally end up as proof you can use a mock framework and little more and don't end up giving you much confidence in your code.
If you are completely new to unit tests and don't have colleges on hand to help set up the environment required for DAL testing you then I'd recommend you leave testing the DAL for now and concentrate on the business logic as this is where you will get the biggest bang for your buck and will make it easier see how the tests will help you.

How to use Moq framework correctly - basic question

I've never used any Mock frameworks and actually new to ASP.NET MVC, testing and all this related stuff.
I'm trying to figure out how to use Moq framework for testing, but can't make it work. that's what I have at the moment: My repository interface:
public interface IUserRepository {
string GetUserEmail();
bool UserIsLoggedIn();
ViewModels.User CurrentUser();
void SaveUserToDb(ViewModels.RegisterUser viewUser);
bool LogOff();
bool LogOn(LogOnModel model);
bool ChangePassword(ChangePasswordModel model);
}
My Controller constuctor, I'm using Ninject for injection, it works fine
private readonly IUserRepository _userRepository;
public HomeController(IUserRepository userRepository) {
_userRepository = userRepository;
}
Simplest method in controller:
public ActionResult Index() {
ViewBag.UserEmail = _userRepository.GetUserEmail();
return View();
}
And my test method:
[TestMethod]
public void Index_Action_Test() {
// Arrange
string email = "test#test.com";
var rep = new Mock<IUserRepository>();
rep.Setup(r => r.GetUserEmail()).Returns(email);
var controller = new HomeController(rep.Object);
// Act
string result = controller.ViewBag.UserEmail;
// Assert
Assert.AreEqual(email, result);
}
I assume that this test must pass, but it fails with message Assert.AreEqual failed. Expected:<test#test.com>. Actual:<(null)>.
What am I doing wrong?
Thanks
Simple - you do not do Act part correctly. Fisrt you should call Index() action of the controller, and then Assert ViewBag.UserEmail correctness
// Act
controller.Index();
string result = controller.ViewBag.UserEmail;
By the way, advice - Using ViewBag is not the good practice. Define ViewModels instead

How do I moq a ISingleResult? Should I? or there is a better method?

I have an action method like this in my controller
public ActionResult Index()
{
using (NorthwindDataContext db = new NorthwindDatacontext())
{
var results = db.GetRecordSets(arg1, ....).ToList();
// use results as list
}
return View();
}
and I wanted to start making tests for it (yes, after it was built, not before... but the code was written before I started to use TDD so... )
and I figured out that adding a property such as this one to the controller
public delegate NorthwindDatacontext ContextBuilderDelegate();
public ContextBuilderDelegate ContextBuilder { get; set; }
I could add in the constructor something like this...
ContextBuilder = () => new NorthwindDatacontext();
then I could test the ActionMethod setting the ContextBuilder property with a mock of NorthwindDatacontext
var controller = new MyController();
var mockDataContext = new Mock<NorthwindDatacontext>();
controller.ContextBuilder = () => mockDataContext.Object;
But... I found no way to use this because all methods of NorthwindDatacontext use ISingleResult as returnType and I cant find the way to create an object with that interface.
I've tried this
var theResult = new List<GetRecordSetsResult>();
// fill the data structure here with the provided result...
mockDataContext.Setup(c => c. GetRecordSets()).Returns(theResult as
ISingleResult<GetRecordSetsResult>);
but it doesn't work because theResult is null when converted to ISingleResult.
Is there any way to create a ISingleResult object to test this way or I'm doing the incorrect way to do things here?
Thanks in Advance
ToList() is an extension method for IEnumerable, which is easy to mock, because it only has one member method -- GetEnumerator().
Still you might have problems mocking NorthwindDataContext class, if its methods are not virtual...
Anyways, that's how I solved a similar problem in my sandbox, hope it helps:
public class MyType
{
public virtual ISingleResult<int> ReturnSomeResult() { throw new NotImplementedException(); }
}
[TestMethod]
public void TestMethod1()
{
var mockMyType = new Mock<MyType>();
var mockSingleResult = new Mock<ISingleResult<int>>();
IEnumerable<int> someEnumerable = new int[] {1,2,3,4,5};
mockSingleResult.Setup(result => result.GetEnumerator()).Returns(someEnumerable.GetEnumerator());
mockMyType.Setup(myType => myType.ReturnSomeResult()).Returns(mockSingleResult.Object);
Assert.AreEqual(15, mockMyType.Object.ReturnSomeResult().ToList().Sum());
}
I created a class that implemented ISingleResult and just put a List in it. I am fairly new to this type of coding, so while this worked for me, use at your own risk (and if you see holes post a comment).
class SingleResult<T>:ISingleResult<T>
{
readonly List<T> _list = new List<T>();
public void Add(T item)
{
_list.Add(item);
}
#region Interface Items
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public object ReturnValue { get { return _list; } }
public void Dispose() { }
#endregion
}
This can then be used to return in part of a mock. This is how I ended up using it with Rhino Mocks:
[TestMethod]
public void TestSomething()
{
//Arrange
// Make a data context and DAL
var _ctx = MockRepository.GenerateMock<IDataClassesDataContext>();
var someDALClass = new SomeDALClass(_ctx);
User testUser = UserObjectHelper.TestUser();
SingleResult<User> userList = new SingleResult<User> { testUser };
// Indicate that we expect a call the to sproc GetUserByUserID
_ctx.Expect(x => x.GetUserByUserID(testUser.UserID)).Return(userList);
//Act
someDALClass.UpdateUser(testUser);
//Assert
Assert.IsTrue(SomeTestCondition());
}

Resources