How to mock HttpContext.User - c#

I am working on a Asp.net MVC 5 project and I am trying to setup a mock to return a custom principal within a controller. I have search and tried different approach suggested but none of them works.
I have a BaseController which all my controllers inherit from. The BaseController has a User property which return HttpContext.User in the getter. The HttpContext.user returns a value when called within the project but return a null when call from a unit test project.
BaseController
public class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; } ***<== Line with issue***
}
}
Custom Principal
public class CustomPrincipal : IPrincipal, ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsStoreUser { get; set; }
public CustomPrincipal(string username)
{
this.Identity = new GenericIdentity(username);
}
}
Controller
public class DocumentsController : BaseController
{
public ViewResult ViewDocuments()
{
var userType = User.IsStoreUser ? UserType.StoreUser : UserType.Corporate; ***<== User is null when calling from a unit test.***
}
}
Test Case
[Test]
public void ViewDocuments_WhenCalled_ShouldReturnViewModel()
{
// Arrange
var principal = new CustomPrincipal("2038786");
principal.UserId = "2038786";
principal.FirstName = "Test";
principal.LastName = "User";
principal.IsStoreUser = true;
var _mockController = new Mock<DocumentsController>(new UnitOfWork(_context)) { CallBase = true };
_mockController.Setup(u => u.User).Returns(principal); ***<== Error - "Invalid setup on a non-virtual (overridable in VB) member: u => u.User"***
// Act
var result = _controller.ViewDocuments();
}
I'm using nUnit and Moq to create the mock object but I not sure what I'm doing wrong. I need to mock the return of User.IsStore in the DocumentControl to return the value of IsStore in the custom principal object i created in the test.

Make a mock http context
private class MockHttpContext : HttpContextBase {
private readonly IPrincipal user;
public MockHttpContext(IPrincipal principal) {
this.user = principal;
}
public override IPrincipal User {
get {
return user;
}
set {
base.User = value;
}
}
}
Arrange test accordingly.
[Test]
public void ViewDocuments_WhenCalled_ShouldReturnViewModel() {
// Arrange
var principal = new CustomPrincipal("2038786");
principal.UserId = "2038786";
principal.FirstName = "Test";
principal.LastName = "User";
principal.IsStoreUser = true;
var mockUoW = new Mock<IUnitOfWork>();
//...setup UoW dependency if needed
var controller = new DocumentsController(mockUoW.Object);
controller.ControllerContext = new ControllerContext {
Controller = controller,
HttpContext = new MockHttpContext(principal)
};
// Act
var result = controller.ViewDocuments();
//Assert
//...assertions
}
Don't mock system under test. Mock its dependencies.

It gets a lot easier if you don't depend on HttpContext directly. Create an IUserProvider interface and an implementation that depends on HttpContext (e.g. HttpContextUserProvider), then stub the IUserProvider in your tests.
The IUserProvider should be passed along to your controller via dependency injection.

Related

Asp.Net MVC 5 Testing IoC + Dependency Injection

I'm trying to test my project. I have never used tests before and I am starting to learn I would like a help, in the simplest case I want test this public ActionResult Index() but I don't know how to Inject those dependencies.
Controller:
Controller:
public class WorkPlacesController : Controller
{
private readonly IWorkPlaceService workPlaceService;
public WorkPlacesController(IWorkPlaceService workPlaceService)
{
this.workPlaceService = workPlaceService;
}
// GET: WorkPlaces
public ActionResult Index()
{
var workPlaces = workPlaceService.GetWorkPlaces(includedRelated:
true);
return View(workPlaces);
}
}
Here is my Service
Service
public class WorkPlaceService : IWorkPlaceService
{
private readonly IWorkPlaceRepository workPlacesRepository;
private readonly IUnitOfWork unitOfWork;
public WorkPlaceService(IWorkPlaceRepository workPlacesRepository, IUnitOfWork unitOfWork)
{
this.workPlacesRepository = workPlacesRepository;
this.unitOfWork = unitOfWork;
}
}
public interface IWorkPlaceService
{
IEnumerable<WorkPlace> GetWorkPlaces(string workPlaceDescription = null, bool includedRelated = true);
}
And my Repository
Repository
public class WorkPlaceRepository : RepositoryBase<WorkPlace>, IWorkPlaceRepository
{
public WorkPlaceRepository(IDbFactory dbFactory)
: base(dbFactory) { }
public WorkPlace GetWorkPlaceByDescription(string workPlaceDescription)
{
var workPlace = this.DbContext.WorkPlaces.Where(c => c.Description == workPlaceDescription).FirstOrDefault();
return workPlace;
}
}
public interface IWorkPlaceRepository : IRepository<WorkPlace>
{
WorkPlace GetWorkPlaceByDescription(string workPlaceDescription);
}
Factory
public class DbFactory : Disposable, IDbFactory
{
AgendaEntities dbContext;
public AgendaEntities Init()
{
return dbContext ?? (dbContext = new AgendaEntities());
}
protected override void DisposeCore()
{
if (dbContext != null)
dbContext.Dispose();
}
}
I tried to do something like this:
public void BasicIndexTest()
{
// Arrange
var mockRepository = new Mock<IWorkPlaceService>();
var controller = new WorkPlacesController(mockRepository.Object);
// Act
ActionResult actionResult = controller.Index() as ViewResult;
// Assert
Assert.IsInstanceOfType(actionResult, typeof(List<WorkPlace>));
}
How do I inject in this controller the data needed to go in the database and bring the results?
I Want test this public ActionResult Index() but I don't know how to Inject those dependencies.
Mock the behavior of required dependencies of the controller for the test and assert the desired behavior when the test is exercised.
For example, based on what you have done so far
public void BasicIndexTest() {
// Arrange
var mockService = new Mock<IWorkPlaceService>();
var workPlaces = new List<WorkPlace>() {
new WorkPlace()
};
mockService
.Setup(_ => _.GetWorkPlaces(It.IsAny<string>(), It.IsAny<bool>()))
.Returns(workPlaces);
var controller = new WorkPlacesController(mockService.Object);
// Act
var actionResult = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(actionResult);
var model = actionResult.Model;
Assert.IsNotNull(model)
Assert.IsInstanceOfType(model, typeof(List<WorkPlace>));
Assert.AreEqual(workPlaces, model);
}
Only the IWorkPlaceService was needed for the testing of Index action, but fake data was needed for the invocation of the GetWorkPlaces method. So the mock was configured to return a list of objects when called and pass it to the view result.

How to Unit Test a controller that dependends on HttpContext

I want to know how to unit test my controller when it inherits from a base controller that is dependent on HttpContext. Below is my inherited controller called BaseInterimController. And below that is the AccountController method that I wish to Unit Test. We are using MOQ.
public abstract class BaseInterimController : Controller
{
#region Properties
protected string InterimName
{
get { return MultiInterim.GetInterimName(InterimIdentifier); }
}
internal virtual string InterimIdentifier
{
get { return System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["InterimIdentifier"].ToString(); }
}
}
public class AccountController : BaseInterimController
{
[HttpPost]
[AllowAnonymous]
[ValidateInput(false)]
[Route(#"{InterimIdentifier:regex([a-z]{7}\d{4})}/Account/Signin")]
public ActionResult Signin(LoginViewModel model)
{
if (ModelState.IsValid)
{
var identity = Authentication.SignIn(model.Username,
model.Password) as LegIdentity;
if (identity != null && identity.IsAuthenticated)
{
return Redirect(model.ReturnUrl);
}
else
{
// Sign in failed
ModelState.AddModelError("",
Authentication.ExternalSignInFailedMessage);
}
}
return View(model);
}
}
Coupling your controller to HttpContext can make your code very difficult to test because during unit tests HttpContext is null unless you try to mock it; which you shouldn't really do. Don't mock code you don't own.
Instead try abstracting the functionality you want to get from HttpContext into something you have control over.
this is just an example. You can try to make it even more generic if needed. I will focus on your specific scenario.
You are calling this directly in your controller
System.Web.HttpContext.Current.Request
.RequestContext.RouteData.Values["InterimIdentifier"].ToString();
When what you are really after is the ability to get that InterimIdentifier value. Something like
public interface IInterimIdentityProvider {
string InterimIdentifier { get; }
}
public class ConcreteInterimIdentityProvider : IInterimIdentityProvider {
public virtual string InterimIdentifier {
get { return System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["InterimIdentifier"].ToString(); }
}
}
which can later be implemented in a concrete class and injected into your controller provided you are using Dependency Injection.
Your base controller will then look like
public abstract class BaseInterimController : Controller {
protected IInterimIdentityProvider identifier;
public BaseInterimController(IInterimIdentityProvider identifier) {
this.identifier = identifier;
}
protected string InterimName {
get { return MultiInterim.GetInterimName(identifier.InterimIdentifier); }
}
//This can be refactored to the code above or use what you had before
//internal virtual string InterimIdentifier {
// get { return identifier.InterimIdentifier; }
//}
}
public class AccountController : BaseInterimController
{
public AccountController(IInterimIdentityProvider identifier)
: base(identifier){ }
[HttpPost]
[AllowAnonymous]
[ValidateInput(false)]
[Route(#"{InterimIdentifier:regex([a-z]{7}\d{4})}/Account/Signin")]
public ActionResult Signin(LoginViewModel model)
{
if (ModelState.IsValid)
{
var identity = Authentication.SignIn(model.Username,
model.Password) as LegIdentity;
if (identity != null && identity.IsAuthenticated)
{
return Redirect(model.ReturnUrl);
}
else
{
// Sign in failed
ModelState.AddModelError("",
Authentication.ExternalSignInFailedMessage);
}
}
return View(model);
}
}
This allows implemented controllers to not be dependent on HttpContext which will allow for better unit testing as you can easily mock/fake IInterimIdentityProvider interface using Moq to return what you want during tests.
[TestMethod]
public void Account_Controller_Should_Signin() {
//Arrange
var mock = new Mock<IInterimIdentityProvider>();
mock.Setup(m => m.InterimIdentifier).Returns("My identifier string");
var controller = new AccountController(mock.Object);
var model = new LoginViewModel() {
Username = "TestUser",
Password = ""TestPassword
};
//Act
var actionResult = controller.Signin(model);
//Assert
//...assert your expected results
}

Mock Request Object for Web API unit test

I want to unit test my web API controller. I have a problem with one of my action method (POST) which is need value from Request object, to get the controller name.
I'm using NSubtitute, FluentAssertions to support my unit test
This is my controller code looks like:
public class ReceiptsController : BaseController
{
public ReceiptsController(IRepository<ReceiptIndex> repository) : base(repository) { }
..... Other action code
[HttpPost]
public IHttpActionResult PostReceipt(string accountId, [FromBody] ReceiptContent data, string userId = "", string deviceId = "", string deviceName = "")
{
if (data.date <= 0)
{
return BadRequest("ErrCode: Save Receipt, no date provided");
}
var commonField = new CommonField()
{
AccountId = accountId,
DeviceId = deviceId,
DeviceName = deviceName,
UserId = userId
};
return PostItem(repository, commonField, data);
}
}
And the base class for my controller :
public abstract class BaseController : ApiController
{
protected IRepository<IDatabaseTable> repository;
protected BaseController(IRepository<IDatabaseTable> repository)
{
this.repository = repository;
}
protected virtual IHttpActionResult PostItem(IRepository<IDatabaseTable> repo, CommonField field, IContent data)
{
// How can I mock Request object on this code part ???
string controllerName = Request.GetRouteData().Values["controller"].ToString();
var result = repository.CreateItem(field, data);
if (result.Error)
{
return InternalServerError();
}
string createdResource = string.Format("{0}api/accounts/{1}/{2}/{3}", GlobalConfiguration.Configuration.VirtualPathRoot, field.AccountId,controllerName, result.Data);
var createdData = repository.GetItem(field.AccountId, result.Data);
if (createdData.Error)
{
return InternalServerError();
}
return Created(createdResource, createdData.Data);
}
}
And this is my unit test for success create scenario:
[Test]
public void PostClient_CreateClient_ReturnNewClient()
{
// Arrange
var contentData = TestData.Client.ClientContentData("TestBillingName_1");
var newClientId = 456;
var expectedData = TestData.Client.ClientData(newClientId);
clientsRepository.CreateItem(Arg.Any<CommonField>(), contentData)
.Returns(new Result<long>(newClientId)
{
Message = ""
});
clientsRepository.GetItem(accountId, newClientId)
.Returns(new Result<ContactIndex>(expectedData));
// Act
var result = _baseController.PostClient(accountId, contentData, userId);
// Asserts
result.Should().BeOfType<CreatedNegotiatedContentResult<ContactIndex>>()
.Which.Content.ShouldBeEquivalentTo(expectedData);
}
I don't know if there is any way to extract Request object from the controller, or maybe is there any way to mock it on the unit test?
Right now this code Request.GetRouteData() return null on the unit test.
you can make an interface for getting Request Data(pass Request object to it). Implement that interface and use as dependency in your Controller. Then you can easily mock this interface implementation in your unit tests.
I've finally find a way to solve this. So basically I have to create some configuration related stuff to make my unit test works.
I create a helpers class for this
public static class Helpers
{
public static void SetupControllerForTests(ApiController controller)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/products");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
}
Then passing my test controller on my test setup
[SetUp]
public void SetUp()
{
clientsRepository = Substitute.For<IRepository<ContactIndex>>();
_baseController = new ClientsController(clientsRepository);
Helpers.SetupControllerForTests(_baseController);
}
I don't know if this is a best way to do it, but I prefer this way instead of create a new interface and inject it to my controller.

How to mock membership provider

How can I mock my membership provider (I have custom membership provider, but don't know how to mock it and give to membership as provider as Membership.Provider has only getter) and use that mocked custom membership provider in my unit test?
Here is my controller
public class MyController
{
private IMyRepository myRepository;
public MyController(IMyRepository myRepository)
{
this.myRepository= myRepository;
}
[HttpGet]
public ActionResult Create()
{
var user = Membership.GetUser(); // <--- I want mock this method
ViewBag.User = user;
return View("Create");
}
}
And here is my test (using Moq)
[TestClass]
public class MyControllerUnitTest
{
private MyController controller;
public MyControllerUnitTest()
{
Mock<IMyRepository > myRepository = new Mock<IMyRepository>();
var controller = new GroupController(myRepository.Object);
}
[TestMethod]
public void TestMethod1()
{
var result = controller.Create() as ViewResult;
Assert.AreEqual("Create", result.ViewName);
}
}
#Sergey is right, you should not use Membership class directly. I know you will need to user Membership class in some cases hence adding following information.
You need to wrap Membership class in a class (derived from an interface) and then you can mock wherever required.
Cut short version of what we have got:
public interface IMembershipService
{
MembershipUser GetUserDetails(string emailAddress);
void CreateUserRole(string roleName);
void AssignUserToRole(string username, string roleName);
bool ValidateUserCredentials(string username, string password);
void SetAuthenticationCookie(string username, bool rememberMe);
void SignOut();
void UpdateUser(MembershipUser membershipUser);
bool DeleteUser(string username);
}
public class MembershipService : IMembershipService
{
public MembershipUser GetUserDetails(string emailAddress)
{
return Membership.GetUser(emailAddress);
}
public MembershipUser GetUserDetails(Guid membershipId)
{
return Membership.GetUser(membershipId);
}
}
In your controller just get it injected:
public class AdminController : Controller
{
private readonly IMembershipService _membershipService;
private readonly IEmailService _emailService;
public AdminController(IMembershipService membershipService,
IEmailService emailService)
{
_membershipService = membershipService;
_emailService = emailService;
}
}
In unit test you can do:
var membershipService = new Mock<IMembershipService>();
First of all you should inherit MyController from the System.Web.Mvc.Controller class:
public class MyController : System.Web.Mvc.Controller
Then you should avoid using the Membership. It's static and it's not designed to be unit testable. The better choice would be to use the controller's User property:
[HttpGet]
public ActionResult Index()
{
ViewBag.UserName = this.User.Identity.Name;
return View("Index");
}
The controller.User property can be mocked using the ControllerContext:
// arrange
Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();
httpContext.SetupGet(c => c.User.Identity.Name).Returns("John Doe");
Mock<ControllerBase> baseControler = new Mock<ControllerBase>();
this.controller.ControllerContext =
new ControllerContext(httpContext.Object, new RouteData(), baseControler.Object);
// act
var result = this.controller.Index();
// assert
Assert.AreEqual("John Doe", ((ViewResult)result).ViewBag.UserName);

Mocking a simple service bus in ASP.NET MVC

I have a simple 'Service' system set up with an interface as shown below. I am trying to mock it for use in my unit testing, but am having a bit of an obstacle. The way it works is that I design classes that implement IRequestFor<T,R> and I would call the service bus like this...
var member = new Member { Name = "valid#email.com", Password = "validPassword" };
ServiceBus.Query<ValidateUser>().With(member);
This works fine in my code. I have no issues with it. But when I try to mock it, like this ..
var service = Mock.Create<IServiceBus>();
// Model
var model = new Web.Models.Membership.Login
{
Email = "acceptible#email.com",
Password = "acceptiblePassword",
RememberMe = true
};
// Arrange
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>().With(model))
.Returns(true);
I am given the following error.
NullReferenceException
I don't even know what the exception is on. It 'points' to the ServiceBus in my Controller code, and if I use the debugger, the object is like .. {IServiceBus_Proxy_2718486e043f432da4b143c257cef8ce}, but other than that, everything else looks the exact same as if I step through it in a normal run.
I am using Telerik JustMock for the mocking, but I don't know how I would do this in a different mocking framework either. I am using Ninject for my Dependency Injection, as well. Can anyone help me?
For convenience, I have included as much of my code as possible below.
Code Reference
Service Bus
public interface IServiceBus
{
T Query<T>() where T : IRequest;
T Dispatch<T>() where T : IDispatch;
}
public interface IRequest
{
}
public interface IDispatch
{
}
public interface IRequestFor<TResult> : IRequest
{
TResult Reply();
}
public interface IRequestFor<TParameters, TResult> : IRequest
{
TResult With(TParameters parameters);
}
public interface IDispatchFor<TParameters> : IDispatch
{
void Using(TParameters parameters);
}
Service Bus Implementation
public class ServiceBus : IServiceBus
{
private readonly IKernel kernel;
public ServiceBus(IKernel kernel) {
this.kernel = kernel;
}
/// <summary>
/// Request a query behavior that may be given parameters to yield a result.
/// </summary>
/// <typeparam name="T">The type of query to request.</typeparam>
/// <returns></returns>
public T Query<T>() where T : IRequest
{
// return a simple injected instance of the query.
return kernel.Get<T>();
}
/// <summary>
/// Request a dispatch handler for a given query that may be given parameters to send.
/// </summary>
/// <typeparam name="T">The type of handler to dispatch.</typeparam>
/// <returns></returns>
public T Dispatch<T>() where T : IDispatch
{
// return a simple injected instance of the dispatcher.
return kernel.Get<T>();
}
}
Service Bus Dependency Injection Wiring (Ninject)
Bind<IServiceBus>()
.To<ServiceBus>()
.InSingletonScope();
Complete Unit Test
[TestMethod]
public void Login_Post_ReturnsRedirectOnSuccess()
{
// Inject
var service = Mock.Create<IServiceBus>();
var authenticationService = Mock.Create<System.Web.Security.IFormsAuthenticationService>();
// Arrange
var controller = new Web.Controllers.MembershipController(
service, authenticationService
);
var httpContext = Mock.Create<HttpContextBase>();
// Arrange
var requestContext = new RequestContext(
new MockHttpContext(),
new RouteData());
controller.Url = new UrlHelper(
requestContext
);
// Model
var model = new Web.Models.Membership.Login
{
Email = "acceptible#email.com",
Password = "acceptiblePassword",
RememberMe = true
};
// Arrange
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>().With(model))
.Returns(true);
// Act
var result = controller.Login(model, "/Home/");
// Assert
Assert.IsInstanceOfType(result, typeof(RedirectResult));
}
Actual Query Method
public class ValidateMember : IRequestFor<IValidateMemberParameters, bool>
{
private readonly ISession session;
public ValidateMember(ISession session) {
this.session = session;
}
public bool With(IValidateMemberParameters model)
{
if (String.IsNullOrEmpty(model.Email)) throw new ArgumentException("Value cannot be null or empty.", "email");
if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("Value cannot be null or empty.", "password");
// determine if the credentials entered can be matched in the database.
var member = session.Query<Member>()
.Where(context => context.Email == model.Email)
.Take(1).SingleOrDefault();
// if a member was discovered, verify their password credentials
if( member != null )
return System.Security.Cryptography.Hashing.VerifyHash(model.Password, "SHA512", member.Password);
// if we reached this point, the password could not be properly matched and there was an error.
return false;
}
}
Login Controller Action
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Login(Web.Models.Membership.Login model, string returnUrl)
{
if (ModelState.IsValid)
{
// attempt to validate the user, and if successful, pass their credentials to the
// forms authentication provider.
if (Bus.Query<ValidateMember>().With(model))
{
// retrieve the authenticated member so that it can be passed on
// to the authentication service, and logging can occur with the
// login.
Authentication.SignIn(model.Email, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Login View Model
public class Login : Membership.Messages.IValidateMemberParameters
{
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(#"^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#(?:[a-z0-9-]+){1}(\.[a-z0-9-]+)*\.([a-z]{2,})$", ErrorMessage = "Invalid Email Address")]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[StringLength(32, MinimumLength = 6)]
[DataType(DataType.Password)]
[RegularExpression(#"^([a-zA-Z0-9##$%]){6,32}$", ErrorMessage = "Invalid Password. Passwords must be between 6 and 32 characters, may contain any alphanumeric character and the symbols ##$% only.")]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
I don't have any real experience with how JustMock works in terms of recursive/nested mocking, but looking at the documentation it may look like that kind of mocking works only if your intermediate chain members are properties. And you're trying to implicitly mock IServiceBus method, which is generic, what can be an obstacle, too.
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>().With(model))
.Returns(true);
You want to set the expectation here on With method from ValidateMember, assuming that the Query<T> method on IServiceBus will be mocked automatically, which may not be a case.
What should work here is to mock it more "traditionally", with two steps - first mock your Query<T> method on IServiceBus to return a mock of ValidateMember, which you should mock to return true.
var validateMemberMock = Mock.Create<Membership.Messages.ValidateMember>();
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>())
.Returns(validateMemberMock);
Mock.Arrange(() => validateMemberMock.With(model))
.Returns(true);
EDIT
Here's my passing code doing more less the same what yours:
[TestClass]
public class JustMockTest
{
public interface IServiceBus
{
T Query<T>() where T : IRequest;
}
public interface IRequest
{
}
public interface IRequestFor<TParameters, TResult> : IRequest
{
TResult With(TParameters parameters);
}
public class ValidateMember : IRequestFor<IValidateMemberParameters, bool>
{
public bool With(IValidateMemberParameters model)
{
return false;
}
}
public class MembershipController
{
private IServiceBus _service;
public MembershipController(IServiceBus service)
{
_service = service;
}
public bool Login(Login model)
{
return _service.Query<ValidateMember>().With(model);
}
}
public interface IValidateMemberParameters
{
}
public class Login : IValidateMemberParameters
{
public string Email;
public string Password;
public bool RememberMe;
}
[TestMethod]
public void Login_Post_ReturnsRedirectOnSuccess()
{
// Inject
var service = Mock.Create<IServiceBus>();
// Arrange
var controller = new MembershipController(service);
// Model
var model = new Login
{
Email = "acceptible#email.com",
Password = "acceptiblePassword",
RememberMe = true
};
var validateMemberMock = Mock.Create<ValidateMember>();
Mock.Arrange(() => service.Query<ValidateMember>())
.Returns(validateMemberMock);
Mock.Arrange(() => validateMemberMock.With(model)).IgnoreArguments()
.Returns(true);
// Act
var result = controller.Login(model);
// Assert
Assert.IsTrue(result);
}
}

Categories