How do I make a unit test to test a method that checks request headers?

后端 未结 3 1087
北海茫月
北海茫月 2021-02-05 18:35

I am very, very new to unit testing and am trying to write a test for a pretty simple method:

public class myClass : RequireHttpsAttribute
{
    public override          


        
3条回答
  •  逝去的感伤
    2021-02-05 19:15

    // arrange
    var context = new Mock();
    var request = new Mock();
    var headers = new NameValueCollection
    {
        { "Special-Header-Name", "false" }
    };
    request.Setup(x => x.Headers).Returns(headers);
    request.Setup(x => x.HttpMethod).Returns("GET");
    request.Setup(x => x.Url).Returns(new Uri("http://www.example.com"));
    request.Setup(x => x.RawUrl).Returns("/home/index");
    context.Setup(x => x.Request).Returns(request.Object);
    var controller = new Mock();
    
    var actionDescriptor = new Mock();
    var controllerContext = new ControllerContext(context.Object, new RouteData(), controller.Object);
    var filterContext = new AuthorizationContext(controllerContext, actionDescriptor.Object);
    var sut = new myClass();
    
    // act
    sut.OnAuthorization(filterContext);
    
    // assert
    Assert.IsInstanceOfType(filterContext.Result, typeof(RedirectResult));
    var redirectResult = (RedirectResult)filterContext.Result;
    Assert.AreEqual("https://www.example.com/home/index", redirectResult.Url);
    

提交回复
热议问题