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

前端 未结 2 1842
盖世英雄少女心
盖世英雄少女心 2021-01-17 23:55

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

相关标签:
2条回答
  • 2021-01-18 00:02

    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.

    0 讨论(0)
  • 2021-01-18 00:04

    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.

    0 讨论(0)
提交回复
热议问题