0

Below is the method in my controller,

public IActionResult Cookiewrite(string key, string value)
{
    CookieOptions options = new CookieOptions();
    options.Expires = DateTime.Now.AddHours(1);
    HttpContext.Response.Cookies.Append(key, value, options);
    return View("Cookiewrite");
}

I am trying to do the test using xUnit, Like below.

 [Fact]
 public void CookieWriteTest()
 {
     string key = "xxxx";
     string value = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
      
     var result = homeController.Cookiewrite(key, value);
  }

but the issue I am getting null error while setting the cookie (Microsoft.AspNetCore.Mvc.ControllerBase.HttpContext.get returned null.). Can anyone please help me with how to do this. as I am new to xUnit.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Udaya
  • 33
  • 4

1 Answers1

1

Change like below:

[Fact]
public void Test1()
{
    var controller = new HomeController();

    //be sure add this...
    controller.ControllerContext.HttpContext = new DefaultHttpContext();

    string key = "xxxxxx";
    string value = "xxxxxxxx";
    var result = controller.Cookiewrite(key, value);
}
Rena
  • 30,832
  • 6
  • 37
  • 72
  • Thank you for the help, it worked. I have another doubt if I want to read a cookie in xUnit what do I have to do? – Udaya Jun 04 '21 at 05:31
  • Hi @Udaya, what is your scenario? Why do you want to read cookie in xUnit? – Rena Jun 04 '21 at 06:24
  • I have a method. In that, I am reading the cookie like this -> string cookieData = Request.Cookies["XXXX"]; the issue is while writing a xUnit I am getting null. – Udaya Jun 04 '21 at 06:33
  • I added a question for this if you can please answer. https://stackoverflow.com/questions/67832702/how-to-mock-and-read-a-cookie-in-xunit – Udaya Jun 04 '21 at 06:55
  • Hi @Udaya,Does the cookieData you read in xUnit project? If so, it seems to be impossible. – Rena Jun 04 '21 at 06:56