Reputation: 13
I wrote a unit test thats failing:
[Test]
public async Task GetLogsPaged_Account_ExpectsSuccess()
{
//Arrange
var request = new Mock<HttpRequest>();
request.Setup(x => x.Scheme).Returns("https");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("https://localhost:5001"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/v1/customersupport-manager/logs/account/D4C88E3C-2848-400F-AB66-0DC3FAFFD24A?PageNumber=1&PageSize=5&DateFrom=2021-09-30%2012%3A30%3A13.413&DateTo=2021-09-30%2012%3A33%3A05.317"));
List<LogEntry> logEntries = new List<LogEntry>() { new LogEntry { Id = 1 }, new LogEntry { Id = 2 } };
PaginationFilter paginationFilter = new PaginationFilter { };
LogEntryListFilter logEntryListFilter = new LogEntryListFilter { };
var accountId = Guid.NewGuid();
LogEntryPageResult logs = new LogEntryPageResult() { PagedRecords = logEntries };
A.CallTo(() => logRepo.GetLogs(A<Guid>._, A<PaginationFilter>._, A<LogEntryListFilter>._)).Returns(logs);
//Act
var result = await svc.GetLogs(accountId, request.Object, paginationFilter, logEntryListFilter);
//Assert
result.ApplicationEvents[0].Code.Should().Be(ApplicationResponseCodes.System.OperationSucceed);
}
When I debug the test I get a exception that says - {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}.
Which can only be var request because it's mocked. I'm not sure why I'm getting this exception when I've seen HttpRequest being mocked in other tests. Any assistance is appreciated.
Edit: I'm including the the line that fails in my code
var uri = new Uri(request.GetDisplayUrl()); <- System.NullReference
But I have the url specified in my tests :
request.Setup(x => x.Scheme).Returns("https");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("https://localhost:5001"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/v1/customersupport-manager/logs/account/D4C88E3C-2848-400F-AB66-0DC3FAFFD24A?PageNumber=1&PageSize=5"));
Upvotes: 1
Views: 909
Reputation: 13009
request.GetDisplayUrl
can't be mocked because it's a static extension method. As usual, the way to do this is to see what the extension method does and mock the underlying object.
In your case you haven't mocked enough. At the time of writing, this is enough for GetDisplayUrl
to work:
var httpRequest = new Mock<HttpRequest>();
httpRequest.SetupGet(req => req.Scheme).Returns("https");
httpRequest.SetupGet(req => req.Host).Returns(new HostString("localhost"));
httpRequest.SetupGet(req => req.PathBase).Returns("");
httpRequest.SetupGet(req => req.Path).Returns("/v1/myApi");
httpRequest.SetupGet(req => req.QueryString).Returns(QueryString.Empty);
Upvotes: 2