我有问题为这个方法编写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);
}