Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mocking

moq

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

like image 905
JohnCambell Avatar asked Sep 13 '12 14:09

JohnCambell


People also ask

Is it possible to unit test Web API?

You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.

Which method is used in the unit testing application in .NET core?

Unit Testing Using XUnit And MOQ In ASP.NET Core.

What can be used for unit testing in .NET solutions?

xUnit. xUnit is a free, open source, community-focused unit testing tool for . NET. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing .


2 Answers

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.

like image 129
Serg Rogovtsev Avatar answered Sep 30 '22 19:09

Serg Rogovtsev


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.

like image 36
sfogle Avatar answered Oct 02 '22 19:10

sfogle