-1
[TestMethod]
public void UnitTestMethod1()
{
   Test1Controller controller = new Test1Controller();

   //This call throws NullReferenceException "Object reference not set to an instance of    an object." 
   WebSecurity.Login("User1", "password1");

   controller.TestMethod(); 
} 

In code above how to make WebSecurity.Login call work?

I did research but it didn't help much

Thanks.

Community
  • 1
  • 1
yW0K5o
  • 913
  • 1
  • 17
  • 32
  • http://stackoverflow.com/questions/12408180/how-to-unit-test-methods-that-use-system-web-security-membership-inside – Neil Thompson Mar 26 '14 at 14:21
  • Thank you, Neil. WebSecurity.Login uses FormsAuthentication.SetAuthCookie which actually throws exception. – yW0K5o Mar 26 '14 at 14:28

1 Answers1

0

You don't want to be testing WebSecurity, only your own code - so you need a way to test your controller action without supplying a real WebSecurity class.

There are lots of ways to do this, but judging by the nature of your question I think you want the simplest approach possible (rather than the most elegant) in which case I would recommend you don't actually test the controller action and all it's associated MVC plumbing, but pull out your logic and just test that, eg:

public Test1Controller
{
      public ActionResult SomeMethod()
      {
            //do mvc stuff

            //do WebSecurity stuff  

            //do your stuff
            MyLogicHere();
      }

    //public only so it can be tested
    public MyLogicHere()
    {
        //the logic in here does not have dependencies on difficult to test types 
    }
}

Then in your test class you are just testing Test1Controller.MyLogicHere (which does not need WebSecuirity).

Either that or really get to grips with DI, Interfaces, Mocks etc...

Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
  • But MyLogicHere uses WebMatrix.WebData.WebSecurity.CurrentUserId. – yW0K5o Mar 26 '14 at 15:20
  • The whole idea is that Test1Controller.SomeMethod() uses WebMatrix.WebData.WebSecurity.CurrentUserId to get the id. You can then pass that id to MyLogicHere() and test MyLogicHere() easily because you only refer to the CurrentUserId and not to WebSecurity – Neil Thompson Mar 26 '14 at 15:27
  • I have to change code to pass CurrentUserId so it diminishes value of Unit testing. – yW0K5o Mar 26 '14 at 15:39