当我在MVC5中使用Mock测试单元获取GetUserId()时,如何编写测试方法?

时间:2017-01-25 12:28:10

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

我有问题为这个方法编写TestMethod(单元测试)。请查看我的代码中的注释,并帮助我更正我的代码。当我测试时,在包含“User.Identity.GetUserId()”调试测试停止的行中,因为userId为null,如何更改此行以便编写正确的单元测试?

// GET: Worts/Create
public ActionResult Create()
{
   return View();
}

// POST: Worts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,CreateDate,ClickCount,DislikeCount,LikeCount, Creator_ID")] Wort wort)
{
  if (ModelState.IsValid)
  {
     wort.CreateDate = DateTime.Now;
     wort.ClickCount = 0;
     wort.DislikeCount = 0;
     wort.LikeCount = 0;


// when I test , in this line Debug testing stop, because userId is null, 
// How can I change this line in order to write correct Unit Test ? 

   var userId = User.Identity.GetUserId();
   wort.Creator = db.Users.Where(x => x.ID == userId).FirstOrDefault();

   db.Worts.Add(wort);
   db.SaveChanges();

   try
   {
     this.mailSender.SendEmail(wort);
     return RedirectToAction("Index");
   }
   catch (Exception)
   {
     throw;
   }
 }
    return View(wort);
}

这是测试方法:

[TestMethod]
public void Create()
{
    // Arrange
    var controller = new WortsController();

    var wort = new LikeWort.Models.Wort();
    wort.Title = "WortTest";

    // Act
    ViewResult result = controller.Create(wort) as ViewResult;

    // Assert
    Assert.IsNotNull(result);
}

1 个答案:

答案 0 :(得分:0)

您可以使用Returns()方法替换1,您可以传递任何值以获取更多信息,请查看this blog

<强> .Returns 从该方法返回的预期结果,该方法必须具有兼容的返回类型, 如果您使用的是NUnit,则必须阅读此Blog

User.Identity.GetUserId().Returns(1)