【问题标题】:Nunit script to test cache data用于测试缓存数据的 Nunit 脚本
【发布时间】:2011-10-02 17:40:51
【问题描述】:

我正在尝试编写一个示例 NUnit 测试脚本来检查缓存中的值

我写了这样的代码

 [TestFixture]

class Authorization
{
    class AutherizationEntity
    {
        public int UserID { get; set; }          
        public int OperationCode { get; set; }
        public bool permission { get; set; }
    }


    [SetUp]
    public void Initialize()
    {

            //if (HttpContext.Current.Cache["UserRights"] == null) 
            //{
                List<AutherizationEntity> AuthorisationObject = new List<AutherizationEntity>();

                for (int i = 0; i < 5; i++)
                {
                    AutherizationEntity AEntity = new AutherizationEntity();
                    AEntity.OperationCode = 10;
                    AEntity.permission = true;
                    AEntity.UserID = i;
                    AuthorisationObject.Add(AEntity);
                }
                HttpContext.Current.Cache.Insert("UserRights", AuthorisationObject);  //Here i am getting the exception in NUnit
            //}

    }

    [TestCase]
    public void AuthorizeUser()
    {           
        int UserId = 1;
        int OperationCode = 10;        
        Boolean HaveRight = false;

        List<AutherizationEntity> AuthEntity = new List<AutherizationEntity>();
        AuthEntity = (List<AutherizationEntity>)HttpContext.Current.Cache.Get("UserRights");

        foreach (AutherizationEntity Auth in AuthEntity)
        {
            if ((Auth.UserID == UserId) && (Auth.OperationCode==OperationCode))
            {
                HaveRight = Auth.permission;
            }
        }

        Assert.AreEqual(HaveRight, true);
    }     

}

但是当我尝试使用 NUnit 运行脚本时,我遇到了异常

Authorization.AuthorizeUser(): SetUp : System.NullReferenceException : 对象引用未设置为对象的实例。

你能帮帮我吗?

【问题讨论】:

    标签: c# testing caching nunit


    【解决方案1】:

    NUnit 不在网络环境中运行,所以HttpContext.Current 为空。如果你想测试它,你需要手动创建一个 we 上下文。

    您可以为您的 httpcontext 创建一个模拟类。请谷歌mock httpcontext,您会发现几个可能对您有用的链接。

    【讨论】:

    • 感谢您的回复。如果您能给我更多解释或有用的链接,可能会有所帮助
    • @san:我没有要展示的具体示例。我在我的帖子中建议了一个可能对你有帮助的谷歌搜索。
    【解决方案2】:

    在测试绑定到 HttpContext 的代码时,您必须依赖抽象并使用假的/存根的 http 上下文。有关该主题的更多信息,请参阅this question。

    不幸的是,缓存对象(和 Cache 类)不能轻易伪造,因为它是一个密封类。可行的方法是创建一个包装类,并在 Cache 对象周围创建一个相应的接口,并在您的测试中对其进行伪造/存根/模拟。

    您可以在 Web 应用程序之外访问 Cache 类,但在这种情况下,您可能不想这样做。可以通过引用 System.Web 程序集并使用 HttpRuntime 类来访问缓存。

    using System.Web;
    using System.Web.Caching;
    …
    Cache cache = HttpRuntime.Cache;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多