Method I'm trying to unit test returns:
return Json(new { ok = true, newurl = Url.Action("Index") });
But this line throws NullReferenceException
which is caused by this part of return:
newurl = Url.Action("Index")
I was trying to make something with:
Request.SetupGet(x => x.Url).Returns(// Data here);
with no effects.
Can You suggest me any solution?
Here is how to mock UrlHelper
using NSubstitute . It would be very similar with other mocking libraries:
UrlHelper Url { get; set; }
[TestFixtureSetUp]
public void FixtureSetUp()
{
var routes = new RouteCollection();
RouteConfig.RegisterRoutes(routes);
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Response.ApplyAppPathModifier(Arg.Any<string>())
.Returns(ctx => ctx.Arg<string>());
var requestContext = new RequestContext(httpContext, new RouteData());
Url = new UrlHelper(requestContext, routes);
}
// Pages
[Test]
public void HomePage()
{
Url.Action("home", "pages").ShouldEqual("/");
}
[Test]
public void PageDetails()
{
Url.Action("details", "pages", new { slug = "contact" }).ShouldEqual("/pages/contact");
}
If you want to attach a mocked UrlHelper to a real Controller, so that when you call an Action on the Controller, it doesn't crash on the UrlHelper, here's what we did (quick and dirty version):
public class MyController : Controller
{
[HttpPost]
public ActionResult DoSomething(int inputValue)
{
var userName = User.UserName();
return Json(new {
redirectUrl = Url.Action("RedirectAction", "RedirectController"),
isRedirect = true,
});
}
}
[Test]
public void Test1()
{
var sb = new StringBuilder();
var response = Substitute.For<HttpResponseBase>();
response.When(x => x.Write(Arg.Any<string>())).Do(ctx => sb.Append(ctx.Arg<string>()));
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Response.Returns(response);
httpContext.User.Identity.Name.Returns("TestUser");
var controller = new MyController();
controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), myController);
controller.Url = Substitute.For<UrlHelper>();
controller.Url.Action(Arg.Any<string>(), Arg.Any<string>()).Returns("anything");
controller.DoSomething(1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.