The controller has this method:
private Person AuthUser() { string personName = Request.Headers["unique_name"]; Person person = new Person(); if (!String.IsNullOrWhiteSpace(personName)) { person = _personService.GetAllPersons().FirstOrDefault(p => p.Email == personName); } return person; } We use it to transfer the object to the service, etc.
[Route("update")] [HttpPut] public bool Update([FromBody]IEnumerable<VacancyModel> vacancyModels) { if (vacancyModels == null || vacancyModels.Count() < 1) { return false; } _vacancyService.UpdateVacancy(vacancyModels, AuthUser()); return true; } For the test, I write the following:
[Fact] public void VacancyController_Update_Test() { _mockVacancyService.Setup(back => back.InsertVacancy(It.IsAny<IEnumerable<Vacancy>>())).Returns(true); //Controller initial _vacancyController = VacancyControllerInit(); var headerDictionary = new HeaderDictionary(); headerDictionary["unique_name"] = "test@test.test"; var request = new Mock<HttpRequest>(); List<StringValues> coll = new List<StringValues>(); coll.Add(headerDictionary["unique_name"]); request.Setup(r => r.Headers.Values).Returns(coll); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(a => a.Request).Returns(request.Object); var cc = new Mock<ControllerContext>(); cc.Setup(b => b.HttpContext).Returns(httpContext.Object); _vacancyController.ControllerContext = cc.Object; Assert.True(_vacancyController.Insert(new List<VacancyModel> { MockedData.VacancyModelItem })); } I tried different variants, or the test ends with errors, and in this case we get Exception:
Because In ASP.NET Core, some interfaces and classes have changed; the working examples are not relevant for my problem right now.
UPDATE:
This problem is solved in the following way:
public ControllerConstructorTest() { var headerDictionary = new HeaderDictionary(); headerDictionary["some"] = "some"; var request = new Mock<HttpRequest>(); List<StringValues> stringValuesCollection = new List<StringValues>(); stringValuesCollection.Add(headerDictionary["unique_name"]); request.Setup(r => r.Headers.Values).Returns(stringValuesCollection); httpContext = new Mock<HttpContext>(); httpContext.SetupGet(a => a.Request).Returns(request.Object); } And further in the test method itself, HttpContext is initialized via the ControllerContext.
Example:
[Fact] public void VacancyController_Update_Test() { _mockVacancyService.Setup(back => back.UpdateVacancy(It.IsAny<IEnumerable<Vacancy>>())).Returns(true); //Controller initial _vacancyController = VacancyControllerInit(); _vacancyController.ControllerContext = new ControllerContext() { HttpContext = httpContext.Object }; Assert.True(_vacancyController.Update(new List<VacancyModel> { MockedData.VacancyModelItem })); } All this is done due to the fact that it will not be possible to install HttpContext directly; it has a read-only property, and this was actually the problem.
