Sometimes, you want certain results based on different combinations of data.
Here's a method that should only call the SearchService methods if a campaign has been selected (CampaignId > 0) and values have been provided to for the PostCode and Distance properties of the Search property:
public async Task<IActionResult> OnGetAsync()
{
if (authService.Allows(User, To.PostCodeSearch))
{
CampaignOptions = new SelectList(await campaignService.GetCampaignsByTypeAsync((int)CampaignTypeOld.Advertising), nameof(Campaign.CampaignId), nameof(Campaign.CampaignName));
if (Search.CampaignId > 0 && !string.IsNullOrWhiteSpace(Search.PostCode) && Search.Distance > 0)
{
Search.OrderBy = OrderBy.Distance;
Search.SortOrder = SortOrder.ASC;
SearchResult = new SearchResult
{
Search = Search,
CompanySearchResults = await searchService.GetRadiusSearchResultAsync(Search),
TotalRecords = await searchService.GetCountForRadiusSearchAsync(Search),
};
}
return Page();
}
return Forbid();
}
Here's how to use Theory and InlineData to test various permutations of search criteria to verify whether the search methods are called under the right conditions:
[Theory]
[InlineData(1, "ValidPostCode", 10, true)] // Should call search methods
[InlineData(0, "ValidPostCode", 10, false)] // Should NOT call search methods (CampaignId is 0)
[InlineData(1, "", 10, false)] // Should NOT call search methods (PostCode is empty)
[InlineData(1, "ValidPostCode", 0, false)] // Should NOT call search methods (Distance is 0)
public async Task RadiusOnGet_ReturnsSearchResult_WhenCriteriaPresent(int campaignId, string postCode, int distance, bool shouldCallSearchMethods)
{
// Arrange
authService.Setup(a => a.Allows(It.IsAny<ClaimsPrincipal>(), To.PostCodeSearch)).Returns(true);
radiusModel.Search = new Search { CampaignId = campaignId, PostCode = postCode, Distance = distance };
// Act
await radiusModel.OnGetAsync();
// Assert
if (shouldCallSearchMethods)
{
searchService.Verify(x => x.GetRadiusSearchResultAsync(It.IsAny<Search>()), Times.Once);
searchService.Verify(x => x.GetCountForRadiusSearchAsync(It.IsAny<Search>()), Times.Once);
}
else
{
searchService.Verify(x => x.GetRadiusSearchResultAsync(It.IsAny<Search>()), Times.Never);
searchService.Verify(x => x.GetCountForRadiusSearchAsync(It.IsAny<Search>()), Times.Never);
}
}
Key Points:
- InlineData is used to feed different combinations of
CampaignId,PostCode, andDistance. - The
Verifymethod checks if the search methods were called (Times.Once) or not called (Times.Never), based on the conditions.