How to unit test methods that use System.Web.Security.Membership inside?

流过昼夜 提交于 2019-12-01 14:39:58

问题


I want to test a method to check that it saves a transaction correctly. Inside it calls Membership.GetUser() to verify the user which causes the test to fail each time. Is there any way to mock this so that Membership.GetUser() always returns a valid name?

I'm using Moq, C# and ASP.Net 4.5 MVC


回答1:


In short, you can't. That's why every call to such a "service" should be hidden behind an abstraction.

You can see a sample of that in default MVC template.




回答2:


Yes, like Serg said, you can mock this by providing an interface for the real service to implement. This interface would have the public methods you are calling, such as:

public interface IMyServiceInterface
{
    IMembershipUser GetUser();
    // other methods you want to use...
}

In your unit tests, you would say:

var mockService = new Mock<IServiceInterface>();
mockService.Setup(mock => mock.GetUser()).
    Returns(new MembershipUserImplementation("MyTestUser", otherCtorParams));

In my example I would create a wrapper for MembershipUser as well as it seems like it also needs to be behind an abstraction.



来源:https://stackoverflow.com/questions/12408180/how-to-unit-test-methods-that-use-system-web-security-membership-inside

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!