Completed
Last Updated: 01 Jul 2025 11:12 by ADMIN
Davy
Created on: 20 Jun 2025 20:36
Type: Feature Request
0
Mocking HttpContext

Good morning,

Could you please give me a help in order to use JustMock to moch the HttpContext of my API controller?

I have inclosed you my code extracted from my software with the minimal code I could.

In this one, DealControllerReadByIdShouldReturnDtos works fine but unfortunately I tried for hour to make my DealControllerReadAllShouldReturnDtos test works.

Could you please help me?

In advance I thank you

Davy MANGOLD - Humrig

Attached Files:
1 comment
ADMIN
Ivo
Posted on: 26 Jun 2025 09:33

Hello Davy,

I hope the following code will be helpful:

[TestMethod]
public void DealControllerReadAllShouldReturnDtos()
{
    var _dto = new DealDto()
    { Id = 1, DealTitle = "TestDeal" };

    var deal = new Deal()
    { Id = 1, DealTitle = "TestDeal" };

    var _dto2 = new DealDto()
    { Id = 2, DealTitle = "TestDeal2" };

    var deal2 = new Deal()
    { Id = 2, DealTitle = "TestDeal2" };

    IEnumerable<DealDto> listDto = new List<DealDto>() { _dto, _dto2 };
    IEnumerable<Deal> list = new List<Deal>() { deal, deal2 };

    Mock.Arrange(() => _mapper.Map<IEnumerable<DealDto>>(list)).Returns(listDto);
    Mock.Arrange(() => _service.ReadAll(Arg.IsAny<Filter>())).ReturnsAsync(list);

    var controller = new DealController(_service, _mapper, _logger);
    var mockHttpContext = Mock.Create<HttpContext>();
    Mock.Arrange(() => controller.HttpContext).Returns(mockHttpContext);

    var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
    string json = JsonConvert.SerializeObject(listDto, typeof(IEnumerable<DealDto>), settings);
    var res = new OkObjectResult(json);

    var res2 = controller.ReadAll().Result;

    Assert.AreEqual(((OkObjectResult)res2).Value, res.Value);
    Assert.AreEqual(((OkObjectResult)res2).StatusCode, res.StatusCode);
}

Regards,
Ivo
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.