atom feed6 messages in com.googlegroups.ninject[ninject] Re: Ninject.Moq
FromSent OnAttachments
Assaf StoneSep 3, 2009 12:00 am 
MiguelSep 5, 2009 11:58 pm 
Miguel MaderoSep 6, 2009 3:57 am 
Miguel MaderoFeb 21, 2010 2:52 pm.cs
teebotFeb 25, 2010 7:51 am 
Miguel MaderoFeb 25, 2010 2:38 pm 
Subject:[ninject] Re: Ninject.Moq
From:Miguel Madero (me@miguelmadero.com)
Date:Feb 21, 2010 2:52:14 pm
List:com.googlegroups.ninject
Attachments:
AccountControllerTests.cs - 15k

I'd suggest that you get familiar first with Mocking and Moq, without using Ninject.Moq. It adds too much magic, which it greats, but to learn how it works it would be easier to take one product at a time.

Attached you will find a the AccountrControllerTest that ships as part of the MVC Apps template, but changed to use XUnit, Moq and Ninject.Moq. I hope this could helped, you can compare this approach to using manual mocking (that's what the original test class is doing) and MSTest to XUnit and Moq.

Notice that I manually created AccountController, since I don't want to mock that class. This could be harder to do if your class rely on dependency injection. To get the kernel to create instances of your classes under test just create a binding for that avoid getting a mock and then just resolve to that type. _kernel.Bind<AccountController>().ToSelf(); _controller = _kernel.Get<AccountController>(); Still all of the dependencies will be mocked.

I didn't use it a lot, so I might be missing something here, but I found that I was writing a lot of setup code on the dependencies that I wanted to mock, so I didn't feel that Ninject.Moq was saving me a lot of time. I could change lines like this and completely get rid of Ninject.Moq: _formsAutheniticationServiceMock = Mock.Get(_controller.FormsAuth); for: _controller.FormsAuth = _formsAutheniticationServiceMock = new Mock<IFormsAuthentication>();

-- Miguel A. Madero Reyes www.miguelmadero.com (blog) me@miguelmadero.com

Hi,

Could someone help me with usage? Where do you instanciate the MockingKernel? Where do I bind?

Do I have to bind the MockingKernel such as kernel.Bind<IRepository>().To< FakeRepository>();

I also tried with:

private MockingKernel kernel; private BandsController bandsController;

[SetUp] public void Init() { kernel = new MockingKernel(); var repo = kernel.Get<IRepository>();

bandsController = new BandsController(); bandsController.Model = repo; }

Mocking is still quite new to me, thanks for you help.

Teebot

-- You received this message because you are subscribed to the Google Groups
"ninject" group. To post to this group, send email to ninj@googlegroups.com. To unsubscribe from this group, send email to
ninject+unsu@googlegroups.com. For more options, visit this group at
http://groups.google.com/group/ninject?hl=en.

using System.Web; using System.Web.Security; using PersonalCook.Web.Controllers; using PersonalCook.Web.Models.Services.Accounts; using PersonalCook.Web.Services.Accounts; using Xunit; using Ninject.Moq; using System.Web.Mvc; using Moq; using System.Web.Routing; using System.Security.Principal;

namespace PersonalCook.Tests.Controllers { public class AccountControllerContext { protected readonly MockingKernel _kernel; protected readonly AccountController _controller; protected readonly Mock<IMembershipService> _memebershipServiceMock; protected readonly Mock<IFormsAuthentication>
_formsAutheniticationServiceMock; protected readonly Mock<HttpContextBase> _httpContextMock; protected Mock<IPrincipal> _userMock; protected Mock<IIdentity> _identityMock;

public AccountControllerContext() { _kernel = new MockingKernel(); _controller = new AccountController(); _kernel.Inject(_controller); _formsAutheniticationServiceMock = Mock.Get(_controller.FormsAuth); _memebershipServiceMock = Mock.Get(_controller.MembershipService); _memebershipServiceMock.Setup(m => m.MinPasswordLength).Returns(6);

_httpContextMock = new Mock<HttpContextBase> { DefaultValue =
DefaultValue.Mock }; var controllerContext = new
ControllerContext(_httpContextMock.Object, new RouteData(), _controller); _controller.ControllerContext = controllerContext; } } public class AccountControllerTests : AccountControllerContext { [Fact] public void ChangePasswordSetsViewDataWithMinPasswordLength() { var result = (ViewResult)_controller.ChangePassword(); Assert.Equal(result.ViewData["PasswordLength"], 6); }

[Fact] public void ChangePasswordRedirectsOnSuccess() { _memebershipServiceMock.Setup(m =>
m.ChangePassword(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Returns(true); var result =
(RedirectToRouteResult)_controller.ChangePassword("oldPass", "newPass",
"newPass"); Assert.Equal("ChangePasswordSuccess", result.RouteValues["action"]); }

[Fact] public void ChangePasswordPostReturnsViewIfCurrentPasswordNotSpecified() { var result = (ViewResult) _controller.ChangePassword("",
"newPassword", "oldPassword"); Assert.Equal("You must specify a current password.",
result.ViewData.ModelState["currentPassword"].Errors[0].ErrorMessage); }

[Fact] public void
ChangePasswordPostReturnsViewIfNewPasswordDoesNotMatchConfirmPassword() { var result =
(ViewResult)_controller.ChangePassword("currentPassword", "newPassword",
"otherPassword"); Assert.Equal("The new password and confirmation password do not
match.", result.ViewData.ModelState["confirmPassword"].Errors[0].ErrorMessage); }

[Fact] public void ChangePasswordPostReturnsViewIfNewPasswordIsNull() { var result =
(ViewResult)_controller.ChangePassword("currentPassword", null, null); Assert.Equal("You must specify a new password of 6 or more
characters.", result.ViewData.ModelState["newPassword"].Errors[0].ErrorMessage); }

[Fact] public void ChangePasswordPostReturnsViewIfNewPasswordIsTooShort() { var result =
(ViewResult)_controller.ChangePassword("currentPassword", "12345", "123453"); Assert.Equal("You must specify a new password of 6 or more
characters.", result.ViewData.ModelState["newPassword"].Errors[0].ErrorMessage); }

[Fact] public void
ChangePasswChangePasswordPostReturnsViewIfProviderRejectsPasswordordRedirectsOnSuccess() { _memebershipServiceMock.Setup(m =>
m.ChangePassword(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Returns(false); var result = (ViewResult)_controller.ChangePassword("oldPass",
"newPass", "newPass"); Assert.Equal("The current password is incorrect or the new password
is invalid.", result.ViewData.ModelState["_FORM"].Errors[0].ErrorMessage); }

[Fact] public void ChangePasswordSuccess() { var result = (ViewResult)_controller.ChangePasswordSuccess(); Assert.NotNull(result); }

[Fact] public void LoginGet() { var result = (ViewResult)_controller.LogOn(); Assert.NotNull(result); }

[Fact] public void LoginPostRedirectsHomeIfLoginSuccessfulButNoReturnUrlGiven() { _memebershipServiceMock.Setup(m =>
m.ValidateUser(It.IsAny<string>(), It.IsAny<string>())).Returns(true); var result = (RedirectToRouteResult)_controller.LogOn("someUser",
"goodPass", true, null); Assert.Equal("Home", result.RouteValues["controller"]); Assert.Equal("Index", result.RouteValues["action"]); }

[Fact] public void
LoginPostRedirectsToReturnUrlIfLoginSuccessfulAndReturnUrlGiven() { _memebershipServiceMock.Setup(m =>
m.ValidateUser(It.IsAny<string>(), It.IsAny<string>())).Returns(true); var result = (RedirectResult)_controller.LogOn("someUser",
"goodPass", true, "someUrl"); Assert.Equal("someUrl", result.Url); }

[Fact] public void LoginPostReturnsViewIfPasswordNotSpecified() { var result = (ViewResult) _controller.LogOn("userName", "", true,
null); Assert.Equal("You must specify a password.",
result.ViewData.ModelState["password"].Errors[0].ErrorMessage); }

[Fact] public void LoginPostReturnsViewIfUsernameNotSpecified() { var result = (ViewResult)_controller.LogOn("", "somePass", true,
null); Assert.Equal("You must specify a username.",
result.ViewData.ModelState["username"].Errors[0].ErrorMessage); }

[Fact] public void LoginPostReturnsViewIfUsernameOrPasswordIsIncorrect() { _memebershipServiceMock.Setup(m =>
m.ValidateUser(It.IsAny<string>(), It.IsAny<string>())).Returns(false); var result = (ViewResult)_controller.LogOn("someUser", "badPass",
true, null); Assert.Equal("The username or password provided is incorrect.",
result.ViewData.ModelState["_FORM"].Errors[0].ErrorMessage); }

[Fact] public void LogOffCallSignOut() { _formsAutheniticationServiceMock.Setup(s=>s.SignOut()).Verifiable(); _controller.LogOff(); _formsAutheniticationServiceMock.Verify(); }

[Fact] public void LogOffRedirectsToHome() { var result = (RedirectToRouteResult)_controller.LogOff(); Assert.Equal("Home", result.RouteValues["controller"]); Assert.Equal("Index", result.RouteValues["action"]); }

[Fact] public void RegisterGet() { var result = (ViewResult)_controller.Register(); Assert.NotNull(result); }

[Fact] public void RegisterPostRedirectsHomeIfRegistrationSuccessful() { _memebershipServiceMock.Setup(s => s.CreateUser(It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(new MembershipCreateResult {
Status = MembershipCreateStatus.Success}); var result = (RedirectToRouteResult)
_controller.Register("someUser", "email", "goodPass", "goodPass"); Assert.Equal("Home", result.RouteValues["controller"]); Assert.Equal("Index", result.RouteValues["action"]); }

[Fact] public void RegisterPostReturnsViewIfEmailNotSpecified() { var result = (ViewResult) _controller.Register("userName", "",
"password", "password"); Assert.Equal("You must specify an email address.",
result.ViewData.ModelState["email"].Errors[0].ErrorMessage); }

[Fact] public void
RegisterPostReturnsViewIfNewPasswordDoesNotMatchConfirmPassword() { var result = (ViewResult)_controller.Register("userName", "email",
"password", "password2"); Assert.Equal("The new password and confirmation password do not
match.", result.ViewData.ModelState["_FORM"].Errors[0].ErrorMessage); }

[Fact] public void RegisterPostReturnsViewIfPasswordIsNull() { var result = (ViewResult)_controller.Register("userName", "email",
null, null); Assert.Equal("You must specify a password of 6 or more characters.",
result.ViewData.ModelState["password"].Errors[0].ErrorMessage); }

[Fact] public void RegisterPostReturnsViewIfPasswordIsTooShort() { var result = (ViewResult)_controller.Register("userName", "email",
"12345", "12345"); Assert.Equal("You must specify a password of 6 or more characters.",
result.ViewData.ModelState["password"].Errors[0].ErrorMessage); }

[Fact] public void RegisterPostReturnsViewIfRegistrationFails() { _memebershipServiceMock.Setup(s => s.CreateUser(It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(new MembershipCreateResult
{Status = MembershipCreateStatus.DuplicateUserName}); _memebershipServiceMock.Setup(m =>
m.ErrorCodeToString(MembershipCreateStatus.DuplicateUserName)).Returns("Username
already exists. Please enter a different user name."); var result = (ViewResult)_controller.Register("userName",
"DuplicateUserName", "password", "password"); Assert.Equal("Username already exists. Please enter a different user
name.", result.ViewData.ModelState["_FORM"].Errors[0].ErrorMessage); }

[Fact] public void RegisterPostReturnsViewIfUsernameNotSpecified() { var result = (ViewResult) _controller.Register("", "email",
"password", "password"); Assert.Equal("You must specify a username.",
result.ViewData.ModelState["username"].Errors[0].ErrorMessage); }

[Fact] public void RegisterPostRedirectsToHomeIfSuccessful() { _memebershipServiceMock.Setup(s => s.CreateUser(It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(new MembershipCreateResult{
Status = MembershipCreateStatus.Success}); var result = (RedirectToRouteResult)
_controller.Register("userName", "email", "password", "password"); Assert.Equal("Home", result.RouteValues["controller"]); Assert.Equal("Index", result.RouteValues["action"]); } } }