views:

240

answers:

3

Hey all,

We're getting some errors, if we try to test something with the asp.net membership framework. It seems that it can't instantiate the asp.net membership environment and so, it can't access all the profiles, users and so on.

Has anybody seen a similar problem? Or is it working for someone?

Cheers, Steve

A: 

The test framework is looking at the test project's web.config file which likely doesn't have the right configuration. You should really write interfaces around the authentication/membership providers and write some dummy implementations to test with.

Daniel A. White
Hi Daniel,The test project usually doesn't have a web.config to put the configuration stuff in there.Cheers,Steve
derSteve
+1  A: 

If you are depending on external resources such as your database and the configuration files (used when using the ASP.NET membership) you aren't writing very effective unit tests. You will have to keep everything in sync including the data in the database. This because a maintenance nightmare.

If you want to test this way, I recommend setting up your configuration to have membership (you can grab this from your application). You then will also want to set up a test database to connect to. It needs to be populated with fake data, so you'll need scripts to make sure the data is consistent.

I would however recommend that you take the approach of doing more proper unit tests. When we refer to a "unit test" we mean testing a very small piece of code at a time. This code should not depend on anything else, so what you need to do is use interfaces and use fakes, stubs, or mocks so that your tests scope is enclosed to a single unit of code.

If you want to go this route I highly recommend reading Working Effectively with Legacy Code. There are also plenty of other books and resources which talk about how to find seams and decouple your code so you're able to test it. Once you get the hang of unit testing you'll be glad you looked into this.

Brendan Enrick
Hi Benrick,Thanks for the good advice.In my case I have a fairly complicated Use Case which involves the membership roles and users. In order to test that, I would realy like to test the whole use case, i.e. test the membership related stuff as well.I'll try to setup the membership in the test project as well.Cheers,Steve
derSteve
A: 

Going on from Benrick's answer - I recommend you take a look at the ASP.NET MVC project - this has examples of the interfaces and wrappers you would need to have to properly unit test your code.

As the comments in the AccountController.cs file state:

The FormsAuthentication type is sealed and contains static members, so it is difficult to unit test code that calls its members. The interface and helper class below demonstrate how to create an abstract wrapper around such a type in order to make the AccountController code unit testable.

Zhaph - Ben Duguid