Answer the question
In order to leave comments, you need to log in
How to test cookies in xUnit?
I'm doing testing, but when I need to add a cookie, I get an error:
NullReferenceException: "Object reference not set to an instance of an object."
var testsP = await controller.GetAllTest();
var testsView = Assert.IsType<ActionResult<List<TestView>>>(testsP);
var testsVw = Assert.IsType<OkObjectResult>(testsView.Result);
var tests = Assert.IsAssignableFrom<List<TestView>>(testsVw.Value);
controller.Response.Cookies.Append("test", new Mock<string>().Object) // Ошибка тут, выдают такую же ошибку в контроллере при добавление cookie
Answer the question
In order to leave comments, you need to log in
0. You have Response or Cookies = null
1. What do you want to test anyway?
2. Why are you trying to do Response.Cookies.Append
3. Google asp net core integration tests
https://www.dotnetcurry.com/aspnet-core/1420/integ...
https://docs.microsoft.com/en -us/aspnet/core/test/...
https://www.syncfusion.com/blogs/post/how-to-integ...
Mock filling the request and response with the controller
Add cookies to httpResponse and httpRequest
I don’t know if this is correct, but I make mocks for myself
#region Mock
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
var httpResponse = new Mock<HttpResponseBase>();
httpResponse.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
var httpRequest = new Mock<HttpRequestBase>();
httpRequest.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
httpRequest.SetupGet(x => x.IsAuthenticated).Returns(false);
httpRequest.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection());
httpRequest.SetupGet(x => x.UserHostAddress).Returns("192.168.1.1");
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(httpRequest.Object);
context.SetupGet(x => x.Response).Returns(httpResponse.Object);
context.SetupGet(x => x.User).Returns(new CustomPrincipal(""));
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
#endregion
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question