I'm currently trying to run a unit test for my web api controller.
Controller:
public async Task<IActionResult> GetCaseById(int id)
{
try
{
var searchedCase = await _caseService.GetByID(id);
return Ok(searchedCase);
} catch(Exception ex)
{
return BadRequest("No case found with that ID");
}
}
Service:
public async Task<Case> GetByID(int id)
{
var searchedCase = await _dataContext.Cases.FirstOrDefaultAsync(c => c.Id == id);
if (searchedCase == null)
throw new NullReferenceException("No user found");
return searchedCase;
}
Unit Test:
public class CaseUnitTest
{
private readonly Mock<ICasesService> casesService;
private readonly CaseController caseController;
public CaseUnitTest()
{
casesService = new Mock<ICasesService>();
caseController = new CaseController(casesService.Object);
}
[Fact]
public void GetCaseByID_ShouldReturnBadRequest_WrongCaseNumber()
{
var result = caseController.GetCaseById(0);
Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
}
}
When I'm calling the method in postman, it returns the BadRequest status. However, When running a unit test, it returns the Ok status. Am I missing something or is there a reason this is happening?