2014-03-26 52 views
-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(); 
} 

在上面的代码中如何使WebSecurity.Login调用工作?用户信息如何从UnitTest传递到控制器?

我没有研究,但它并没有帮助much

感谢。

+0

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

+0

谢谢,尼尔。 WebSecurity.Login使用FormsAuthentication.SetAuthCookie,它实际上会引发异常。 – yW0K5o

回答

0

你不想测试WebSecurity,只有你自己的代码 - 所以你需要一种方法来测试你的控制器动作,而不需要提供真实的 WebSecurity类。

有很多方法可以做到这一点,但您的问题的性质来看,我认为你想最简单的方法可能(而不是最优雅的),在这种情况下,我会建议你实际上并不测试控制器动作和所有它相关的MVC管道,但拿出你的逻辑和公正的测试,如:

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 
    } 
} 

然后在您的测试类,你只是测试Test1Controller.MyLogicHere(这并不需要WebSecuirity)。

如果不是这样,真正到了与DI,接口,嘲弄等交手......

+0

但MyLogicHere使用WebMatrix.WebData.WebSecurity.CurrentUserId。 – yW0K5o

+0

整个想法是Test1Controller.SomeMethod()使用WebMatrix.WebData.WebSecurity.CurrentUserId来获取id。然后,您可以将该ID传递给MyLogicHere()并轻松测试MyLogicHere(),因为您只需引用CurrentUserId,而不是WebSecurity –

+0

我必须更改代码以传递CurrentUserId,这样会降低单元测试的价值。 – yW0K5o

相关问题