【问题标题】:How could User info be passed from UnitTest to controller?用户信息如何从 UnitTest 传递到控制器?
【发布时间】:2014-03-26 14:17:19
【问题描述】:
[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 调用起作用?

我做了研究,但没有帮助much

谢谢。

【问题讨论】:

标签: c# asp.net-mvc unit-testing


【解决方案1】:

您不想测试 WebSecurity,只想测试您自己的代码 - 所以您需要一种方法来测试您的控制器操作,而无需提供 real 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、接口、Mocks 等......

【讨论】:

  • 但 MyLogicHere 使用 WebMatrix.WebData.WebSecurity.CurrentUserId。
  • 整个想法是 Test1Controller.SomeMethod() 使用 WebMatrix.WebData.WebSecurity.CurrentUserId 来获取 id。然后,您可以将该 id 传递给 MyLogicHere() 并轻松测试 MyLogicHere(),因为您只引用 CurrentUserId 而不是 WebSecurity
  • 我必须更改代码以传递 CurrentUserId,这样它会降低单元测试的价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多