具有业务逻辑和单元测试的表单身份验证

发布于 2024-10-17 09:38:37 字数 402 浏览 0 评论 0原文

我的业务类有一个方法“Save”,当调用它时,它应该自动将 MyObject.AspNetUserId (guid 属性)设置为 Membership.GetUser().ProviderUserKey,然后实际执行保存。我编写了代码,但我在单元测试时遇到问题。

在我的单元测试中,我有一行“FormsAuthentication.SetAuthCookie”,测试正在中断。我假设这是因为我的单元测试没有在 HTTP 上下文中运行,所以它实际上无法设置 cookie。

有没有办法让它工作,或者我只需要在演示网站上手动测试它?

这是一个非常糟糕的做法吗?我应该做点别的事情吗?这段代码的目标是让我的对象的“CreatedBy”和“EditedBy”属性自动设置,这样程序员就不必每次都在网站代码中记住。如果有人有更好的方法,我愿意接受想法。

My business class has a method "Save" that when it is called it should automatically set MyObject.AspNetUserId (a guid property) to Membership.GetUser().ProviderUserKey then actually perform the save. I wrote the code but I am having an issue unit testing this.

In my unit test I have a line "FormsAuthentication.SetAuthCookie" that the test is breaking on. I'm assuming that is because my unit test is not being run within an HTTP context so it can't actually set the cookie.

Is there a way to get this to work or do I just have to manually test it on the demo site?

Is this a really bad practice and I should be doing something else? The goal of this code is to have the "CreatedBy" and "EditedBy" properties of my object set themselves automatically so the programmer doesn't have to remember to every time in the website code. If anybody has a better method I'm open to ideas.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅语花开 2024-10-24 09:38:37

针对授权接口编写所有授权调用怎么样?这样,您就可以允许在单元测试期间替换其实现,并设置调用登录方法的期望。

这是一个例子:

   public interface IAuthorization
    {
        bool ValidateUser(LoginUser u, string password);
        LoginUser GetCurrentUser();
        void LogIn(LoginUser user);
        void LogOut();
        IIdentity GetCurrentUserIdentity();
    }

What about programming all authorization calls against an authorization interface? That way you can allow its implementation to be substituted during unit tests and set up expectations that the login method is called.

Here is an example:

   public interface IAuthorization
    {
        bool ValidateUser(LoginUser u, string password);
        LoginUser GetCurrentUser();
        void LogIn(LoginUser user);
        void LogOut();
        IIdentity GetCurrentUserIdentity();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文