I am new to unit testing .net applications and am having difficulty with what I would imagine to be a very simple case.
// GET: Entities
public ViewResult Index()
{
_User = UserManager.FindById(User.Identity.GetUserId());
return View(entityRepository.GetEntities(_User.entityId));
}
I want to test that the correct view is outputted but can't get past the user line. In other languages I would simply mock UserManager.FindById to always return some predefined object, but I can't get it to work.
Have been trying to follow the approach given here example mocking the IUserStore but can't get it to work with my example. To mock FindByNameAsync they have used store.As
Any advice would be gratefully received.
My attempt was to follow a similar method to that in link above. Obviously IUserPasswordStore is the wrong interface, but I am not sure how to find the correct one.
var store = new Mock<IUserStore<ApplicationUser>>(MockBehavior.Strict);
store.As<IUserPasswordStore<ApplicationUser>>()
.Setup(x => x.FindById(It.IsAny<string>()))
.Returns(ApplicationUser)null);
EntitiesController controller = new EntitiesController();
var result = controller.Index() as ViewResult;
Assert.AreEqual("Index", result.ViewName);
So, thanks to the guidance from #Nkosi and #haim770 I think I have an answer. It still seems overly complex though, so would be interested to hear if you know how to simplify.
It started with needing to write more testable code, I installed Unity and started to inject dependencies allowing me to mock them out.
The solution that passes is:
Mock<IPrincipal> mockPrincipal;
string username = "test#test.com";
[TestInitialize]
public void TestInitialize()
{
//Arrange
var identity = new GenericIdentity(username, "");
var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
identity.AddClaim(nameIdentifierClaim);
mockPrincipal = new Mock<IPrincipal>();
mockPrincipal.Setup(x => x.Identity).Returns(identity);
mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);
}
[TestMethod]
public void EntitiesIndexDisplaysTheDefaultView()
{
var context = new Mock<HttpContextBase>();
var principal = mockPrincipal.Object;
context.Setup(x => x.User).Returns(principal);
var userManagerMock = new Mock<IUserStore<ApplicationUser>>(MockBehavior.Strict);
userManagerMock.As<IUserPasswordStore<ApplicationUser>>()
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new ApplicationUser() { entityId = "id" });
var entitiesRepositoryMock = new Mock<IEntityRepository>();
entitiesRepositoryMock
.Setup(x => x.GetEntities(It.IsAny<string>()))
.Returns((IEnumerable<Entity>)new List<Entity>());
EntitiesController controller = new EntitiesController(new UserManager<ApplicationUser>(userManagerMock.Object),
entitiesRepositoryMock.Object);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("", result.ViewName);
}
Related
We have the following lines in one of the functions in the MVC controller.
public ActionResult EditEmp(int eId = 0)
{
EPermission ePermission = (EPermission)HttpContext.Items["empPermission"];
}
In my unit test, I am calling this controller to test.
public void TestMethod1()
{
var result = eController.EditEmp(10) as ViewResult;
}
My test case fails because there is no value in the HttpContext for empPermission during the runtime.
We are wondering how can we populate the HttpContext.Items with a value so it can pick up during the runtime. We have look for some examples in mock, but not any luck so far.
You need to mock the HttpContext. Here is an example of code that should run in your unit test (preferably on TestInitialize) before calling your controller method:
var httpRequest = new HttpRequest("", "http://mySomething/", "");
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
HttpContext.Current = httpContext;
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity("WSUSER"),
new string[0]
Possible repeat of Mock HttpContext.Current in Test Init Method
I have this function and unit test.
ProfileController Code
[HttpPost]
public ActionResult Edit(int? id)
{
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });
return Json(new { Url = redirectUrl });
}
unit test code
[TestMethod]
public void TestDetailsViewData()
{
var controller = new ProfileController(_Profile);
var result = controller.Edit(1) as ViewResult;
var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model;
Assert.AreEqual("Testor", profile.cardName);
}
i would like to test this function and this function will redirect to index page and return ViewPage with data. But the problem is when i run this unit test code i got Null exception at this line ,because of the Request is NULL
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });
so may i know how could i test this?
Updated with Moq function
After further reading and get some sample code from here it seem request able to filled with value but now the RequestContext is NULL, anyone can point me to right place for me to study?
[TestMethod]
public void TestDetailsViewData()
{
var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
//context.SetupGet(x => x.Request.RequestContext ).Returns(request.Object.RequestContext);
var controller = new ProfileController(_Profile);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
controller.Request.RequestContext = context.Object.Request.RequestContext;
var result = controller.Edit(1) as ViewResult;
var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model;
Assert.AreEqual("testor", profile.cardName);
}
The error is occurring because the request is not defined in Test method.I think you have to use visual studio fakes.
https://msdn.microsoft.com/en-us/library/hh549175.aspx
I have the following unit test defined to test my model binder:
[TestMethod]
public void DateTime_Works() {
// Arrange
var controllerContext = FakeContext.GetAuthenticatedControllerContext(new Mock<Controller>().Object, "TestAdmin");
var values = new NameValueCollection {
{ "Foo.Date", "12/02/1964" },
{ "Foo.Hour", "12" },
{ "Foo.Minute", "00" },
{ "Foo.Second", "00" }
};
var bindingContext = new ModelBindingContext() { ModelName = "Foo", ValueProvider = new NameValueCollectionValueProvider(values, null) };
var binder = new DateAndTimeModelBinder();
// Act
var result = (DateTime)binder.BindModel(controllerContext, bindingContext);
// Assert
Assert.AreEqual(DateTime.Parse("1964-12-02 12:00:00"), result);
}
Here is the FakeContext class:
public static class FakeContext {
public static HttpContextBase GetHttpContext(string username) {
var context = new Mock<HttpContextBase>();
context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));
return context.Object;
}
public static ControllerContext GetControllerContext(Controller controller) {
return GetAuthenticatedControllerContext(controller, null);
}
public static ControllerContext GetAuthenticatedControllerContext(Controller controller, string username) {
var httpContext = GetHttpContext(username);
return new ControllerContext(httpContext, new RouteData(), controller);
}
}
Within my model binder i call a utility method which has the following line in it:
HttpContext.Current.User.Identity.IsAuthenticated
This seems to always return false even when I pass a username in. I was wondering how the GetHttpContext method can be modified to mock this out aswell.
I'd appreciate the help. Thanks
You are mocking the IsAuthenticated property of the Request and not of the User Identity. Your mock is indicating that the request has been authenticated, but has nothing to do with the identity authentication.
Changing your mock up a little should fix your problem.
var identityMock = new Mock<IIdentity>();
identityMock.SetupGet( i => i.IsAuthenticated ).Returns( !string.IsNullOrEmpty(username));
var userMock = new Mock<IPrincipal>();
userMock.SetupGet( u => u.Identity ). Returns( identityMock.Object );
var context = new Mock<HttpContextBase>();
context.SetupGet( ctx => ctx.User ).Returns( userMock.Object );
Edit The more I thought about it the more I felt these mocks needed to be setup seperatly
Note, I have not executed this code. It should get you what you need however.
MSDN for Request.IsAuthenticated
http://msdn.microsoft.com/en-us/library/system.web.httprequest.isauthenticated.aspx
MSDN for User.Identity.IsAuthenticated
http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.isauthenticated.aspx
Hope this helps.
You could use Moq and follow the advice found here:
Moq: unit testing a method relying on HttpContext
Is it possible to get the resulting HTML that is outputting from an action via code?
Check out MvcIntegrationTestFramework
To be specific on why you would look at MvcIntegrationTestFramework.
It makes saves you writing your own helpers to stream result and is proven to work well enough. I'd assume this would be in a test project and as a bonus you would have the other testing capabilities once you've got this setup. Main bother would probably be sorting out the dependency chain.
private static readonly string mvcAppPath =
Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory
+ "\\..\\..\\..\\MyMvcApplication");
private readonly AppHost appHost = new AppHost(mvcAppPath);
[Test]
public void Root_Url_Renders_Index_View()
{
appHost.SimulateBrowsingSession(browsingSession => {
RequestResult result = browsingSession.ProcessRequest("");
Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
});
}
Here is an example of how I have done it in Razor syntax. I needed to get the html from one action as a string in another action (to the render as a pdf)
ViewResult viewResult = ActionYouWhatHtmlFrom(id);
using (var writer = new StringWriter())
{
ViewEngineResult result = ViewEngines
.Engines
.FindView(ControllerContext,
viewResult.ViewName, "_YourLayout");
var viewPath = ((RazorView)result.View).ViewPath;
var layoutPath = ((RazorView) result.View).LayoutPath;
var view = new RazorView(ControllerContext, viewPath, layoutPath, true, null);
var viewCxt = new ViewContext(
ControllerContext,
view,
viewResult.ViewData,
viewResult.TempData, writer);
viewCxt.View.Render(viewCxt, writer);
I have a controller in C# using the ASP.Net MVC framework
public class HomeController:Controller{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//do some ajaxy stuff
}
return View("Index");
}
}
I got some tips on mocking and was hoping to test the code with the following and RhinoMocks
var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
var controller = new HomeController();
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);
However I keep getting this error:
Exception
System.ArgumentNullException:
System.ArgumentNullException : Value
cannot be null. Parameter name:
request at
System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase
request)
Since the Request object on the controller has no setter. I tried to get this test working properly by using recommended code from an answer below.
This used Moq instead of RhinoMocks, and in using Moq I use the following for the same test:
var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers["X-Requested-With"]).Returns("XMLHttpRequest");
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new HomeController(Repository, LoginInfoProvider);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);
but get the following error:
Exception System.ArgumentException:
System.ArgumentException : Invalid
setup on a non-overridable member: x
=> x.Headers["X-Requested-With"] at Moq.Mock.ThrowIfCantOverride(Expression
setup, MethodInfo methodInfo)
Again, it seems like I cannot set the request header.
How do I set this value, in RhinoMocks or Moq?
Using Moq:
var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
UPDATED:
Mock Request.Headers["X-Requested-With"] or Request["X-Requested-With"] instead of Request.IsAjaxRequest().
For anyone using NSubstitute I was able to modify the above answers and do something like this... (where Details is the Action method name on the controller)
var fakeRequest = Substitute.For<HttpRequestBase>();
var fakeContext = Substitute.For<HttpContextBase>();
fakeRequest.Headers.Returns(new WebHeaderCollection { {"X-Requested-With", "XMLHttpRequest"}});
fakeContext.Request.Returns(fakeRequest);
controller.ControllerContext = new ControllerContext(fakeContext, new RouteData(), controller);
var model = new EntityTypeMaintenanceModel();
var result = controller.Details(model) as PartialViewResult;
Assert.IsNotNull(result);
Assert.AreEqual("EntityType", result.ViewName);
Here is a working solution using RhinoMocks. I've based it on a Moq solution I found at http://thegrayzone.co.uk/blog/2010/03/mocking-request-isajaxrequest/
public static void MakeAjaxRequest(this Controller controller)
{
MockRepository mocks = new MockRepository();
// Create mocks
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
// Set headers to pretend it's an Ajax request
SetupResult.For(mockedHttpRequest.Headers)
.Return(new WebHeaderCollection() {
{"X-Requested-With", "XMLHttpRequest"}
});
// Tell the mocked context to return the mocked request
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
mocks.ReplayAll();
// Set controllerContext
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
}
Is AjaxRequest is an extension method. So you can do it the following way using Rhino:
protected HttpContextBase BuildHttpContextStub(bool isAjaxRequest)
{
var httpRequestBase = MockRepository.GenerateStub<HttpRequestBase>();
if (isAjaxRequest)
{
httpRequestBase.Stub(r => r["X-Requested-With"]).Return("XMLHttpRequest");
}
var httpContextBase = MockRepository.GenerateStub<HttpContextBase>();
httpContextBase.Stub(c => c.Request).Return(httpRequestBase);
return httpContextBase;
}
// Build controller
....
controller.ControllerContext = new ControllerContext(BuildHttpContextStub(true), new RouteData(), controller);
Looks like you are looking for this,
var requestMock = new Mock<HttpRequestBase>();
requestMock.SetupGet(rq => rq["Age"]).Returns("2001");
Usage in Controller :
public ActionResult Index()
{
var age = Request["Age"]; //This will return 2001
}
In current .NET (v 5):
var controller = new SomeController(); // SomeController that inherits Microsoft.AspNetCore.Mvc.ControllerBase
var httpContext = new DefaultHttpContext(); // DefaultHttpContext class is part of Microsoft.AspNetCore.Http namespace
httpContext.Request.Headers.Add("origin", "0.0.0.1"); // Add your custom headers to request
controller.ControllerContext.HttpContext = httpContext;
You need to mock HttpContextBase and put it into your ControllerContext property, like that:
controller.ControllerContext =
new ControllerContext(mockedHttpContext, new RouteData(), controller);
To make IsAjaxRequest() to return false during Unit test you need to setup Request Headers as well as request collection value both in your test method as given below:
_request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection { { "X-Requested-With", "NotAjaxRequest" } });
_request.SetupGet(x=>x["X-Requested-With"]).Returns("NotAjaxRequest");
The reason for setting up both is hidden in implementation of IsAjaxRequest() which is given below:
public static bool IsAjaxRequest(this HttpRequestBase request)<br/>
{
if (request == null)
{
throw new ArgumentNullException("request");
}
return ((request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest")));
}
It uses both request Collection and header this is why we need to create setup for both Header and Request Collection.
this will make the request to return false when it is not a ajax request. to make it return true you can do the following:
_httpContext.SetupGet(x => x.Request["X-Requested-With"]).Returns("XMLHttpRequest");
I found other way to add a HttpRequestMessage object into your request during Web API as follow
[Test]
public void TestMethod()
{
var controllerContext = new HttpControllerContext();
var request = new HttpRequestMessage();
request.Headers.Add("TestHeader", "TestHeader");
controllerContext.Request = request;
_controller.ControllerContext = controllerContext;
var result = _controller.YourAPIMethod();
//Your assertion
}
(A bit late to the party but I went for a different route so thought I'd share)
To go for a pure code/mocking way of testing this without creating mocks for Http classes I implemented an IControllerHelper which has an Initialise method which takes the Request as a parameter and then exposed properties I want eg:
public interface IControllerHelper
{
void Initialise(HttpRequest request);
string HostAddress { get; }
}
public class ControllerHelper : IControllerHelper
{
private HttpRequest _request;
public void Initialise(HttpRequest request)
{
_request = request;
}
public string HostAddress => _request.GetUri().GetLeftPart(UriPartial.Authority);
}
Then in my controller I call initialise at the start of the method:
_controllerHelper.Initialise(Request);
And then my code is only dependent on mockable dependacies.
return Created(new Uri($"{_controllerHelper.HostName}/api/MyEndpoint/{result.id}"), result);
For functional tests I just override the iControllerHelper in the composition for a substitute.