【问题标题】:unit test http module, check http status code单元测试http模块,检查http状态码
【发布时间】:2012-12-03 21:49:11
【问题描述】:

我不明白为什么这个单元测试不起作用。它基于此处找到的代码示例: http://weblogs.asp.net/rashid/archive/2009/03/12/unit-testable-httpmodule-and-httphandler.aspx

[Test]
public void when_user_doesnt_authenticate_returns_304_status()
{
    _httpContext = new Mock<HttpContextBase>();
    _httpRequest = new Mock<HttpRequestBase>();
    _httpResponse = new Mock<HttpResponseBase>();          

    _httpContext.SetupGet(context => context.Request).Returns(_httpRequest.Object);        

    var module = new TAS.HttpModule.TASHttpModule();         
    _httpResponse.SetupSet(response => response.StatusCode = 304).Verifiable();
    _httpContext.SetupGet(context => context.Response).Returns(_httpResponse.Object);         
    module.OnAuthenticateRequest(_httpContext.Object);   
    _httpResponse.VerifyAll();

}

http 模块中的代码(简化以演示问题)

public class TASHttpModule : BaseHttpModule

 public override void OnAuthenticateRequest(HttpContextBase context)
 {

    HttpResponseBase response = context.Response;
    response.StatusCode = 403;
    response.StatusDescription = "Access Denied";
    response.End();
 }
}
public class BaseHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += (sender, e) => OnBeginRequest(new HttpContextWrapper(((HttpApplication)sender).Context));
            context.Error += (sender, e) => OnError(new HttpContextWrapper(((HttpApplication)sender).Context));
            context.EndRequest += (sender, e) => OnEndRequest(new HttpContextWrapper(((HttpApplication)sender).Context));
            context.AuthenticateRequest += (sender, e) => OnAuthenticateRequest(new HttpContextWrapper(((HttpApplication)sender).Context));
        }

        public void Dispose()
        {
        }

        public virtual void OnBeginRequest(HttpContextBase context)
        {
        }

        public virtual void OnError(HttpContextBase context)
        {
        }

        public virtual void OnEndRequest(HttpContextBase context)
        {
        }
        public virtual void OnAuthenticateRequest(HttpContextBase context)
        {
        }
    }

基本问题是无法设置response.StatusCode值。它总是回到零。所以检查 304 状态的测试总是失败。任何帮助将不胜感激!

【问题讨论】:

    标签: asp.net nunit moq httpmodule


    【解决方案1】:

    我刚刚设法证明 304 和 403 不相等。自我注意:直接使用http状态码枚举而不是数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 2023-03-02
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2014-08-03
      相关资源
      最近更新 更多