0

I have problem to write TestMethod (Unit Test) for this method. Please see the comment in my code and help me to correct my code. when I test , in the line which contain "User.Identity.GetUserId()" Debug testing stop, because userId is null, How can I change this line in order to write correct Unit Test ?

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

this is the Test Method :

[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);
}
Sara
  • 33
  • 6
  • which unit testing framework are you using ? can u show your test method? – esiprogrammer Jan 25 '17 at 12:34
  • @esiprogrammer I added my thest Method to my Question – Sara Jan 25 '17 at 12:53
  • Sara you can use moq library to achieve this. have a look at [this question](http://stackoverflow.com/questions/19006624/how-to-mock-httpcontext-user-identity-name-in-asp-net-mvc-4) hope it helps – esiprogrammer Jan 25 '17 at 13:08
  • I Used that Question , Still Debug Test stop in same line (User.Identity.GetuserId() . – Sara Jan 25 '17 at 13:20
  • in that question it doesn't moq GetUserId method. it uses `HttpContext.Current.User.Identity.Name`. you need to moq GetUserId like `fakeIdentity.Setup(f => f.GetUserId()).Returns(1); ` – esiprogrammer Jan 25 '17 at 13:27

1 Answers1

0

You can use Returns() method in replace of 1 you can pass any value for more information take a look at this blog

.Returns The expected result to be returned from the method, which must have a compatible return type, if you are using NUnit you have to read this Blog

User.Identity.GetUserId().Returns(1)
Curiousdev
  • 5,668
  • 3
  • 24
  • 38