In ASP.NET Core unit tests, if you want to mock HttpClient.GetStringAsync(), here's the trick. Problem Given the following code var html = await _httpClient.GetStringAsync(sourceUrl); When I tried to mock HttpClient.GetStringAsync() like this var httpClientMock = new Mock<HttpClient>(); httpClientMock .Setup(p => p.GetStringAsync(It.IsAny<string>())) .Returns(Task.FromResult("...")); Moq …
In ASP.NET Core unit tests, if you want to mock HttpContext.Features.Get<SomeType>(), here's the trick. Problem I have my Error page code that will get exception detail infomation, to do that, I use HttpContext.Features.Get<IExceptionHandlerPathFeature>(). public void OnGet() { var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; var exceptionFeature = HttpContext.Features. …
Problem
In ASP.NET Core, when you use extension methods on UrlHelperExtensions class, it would be difficult to write Mock in unit test. Because Moq doesn't support mocking extension methods.
For example, the following code that I use in my blog is using Url.Page() method:
var callbackUrl = Url.Page("/Index", null, null, Request.Scheme);
But in my unit test, mocking like this will throw …