0

我不明白为什么这个单元测试不起作用。它基于此处找到的代码示例: 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 状态的测试总是失败。任何帮助将不胜感激!

4

1 回答 1

-1

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

于 2012-12-04T02:29:50.400 回答