【问题标题】:How can I write Test Method when I have GetUserId() by Mock - Test Unit in MVC5? [duplicate]当我通过 Mock - MVC5 中的测试单元获得 GetUserId() 时,如何编写测试方法? [复制]
【发布时间】:2017-01-25 12:28:10
【问题描述】:

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

// 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);
}

【问题讨论】:

  • 您使用的是哪个单元测试框架?可以展示一下你的测试方法吗?
  • @esiprogrammer 我将我的方法添加到我的问题中
  • Sara 你可以使用 moq 库来实现这一点。看看this question希望对你有帮助
  • 我使用了那个问题,仍然在同一行调试测试停止 (User.Identity.GetuserId()。
  • 在那个问题中它没有起订量 GetUserId 方法。它使用HttpContext.Current.User.Identity.Name。你需要起订量 GetUserId 像 fakeIdentity.Setup(f => f.GetUserId()).Returns(1);

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


【解决方案1】:

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

.返回 从方法返回的预期结果,它必须具有兼容的返回类型, 如果你使用 NUnit,你必须阅读这个Blog

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

【讨论】:

  • 我添加了 .Returns(1) ... 但出现错误“字符串不包含返回的定义 ...
  • 因为 GetUserId() 方法的返回类型是字符串尝试解析“1”字符串中的 1
  • 还是一样的错误...
  • 哦,一分钟你模拟了 HttpContext 吗?
  • 我想使用模拟,但我不知道如何......请再次查看我的代码以及我现在添加到我的问题中的测试方法
猜你喜欢
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2019-06-06
相关资源
最近更新 更多