mardi 26 septembre 2017

How to test methods with attributes with asp.net core 2?

My project is an ASP.NET Core 2.0 web application.

How can I test if my own written attribute is working fine by calling a method containing the attribute?

For example:

Attribute

[AttributeUsage(AttributeTargets.Method)]
public class ValidateUserLoggedInAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext context)
  {
     var controller = (BaseController)context.Controller;
     if (!controller.UserRepository.IsUserLoggedIn)
     {
        var routeValueForLogin = new RouteValueDictionary(new { action = "Login", controller = "Home", area = "" });
        context.Result = new RedirectToRouteResult(routeValueForLogin);
     }
  }
}

Controller:

[ValidateUserLoggedIn]
public IActionResult Start()
{
    ...
}

Test:

[TestMethod]
public void Test()
{
    // Act
    var result = this.controllerUnderTest.Start() as RedirectToRouteResult;

    // Assert
     Assert.IsNotNull(result);
     Assert.IsFalse(result.Permanent);

     var routeValues = result.RouteValues;

     const string ControllerKey = "controller";
     Assert.IsTrue(routeValues.ContainsKey(ControllerKey));
     Assert.AreEqual("Home", routeValues[ControllerKey]);

     const string ActionKey = "action";
     Assert.IsTrue(routeValues.ContainsKey(ActionKey));
     Assert.AreEqual("Login", routeValues[ActionKey]);
}

I have already written a test only for the attribute by creating an ActionExecutingContext, but I also want to test it for the controller method.

Aucun commentaire:

Enregistrer un commentaire