Reputation: 21
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?
Upvotes: 1
Views: 16
Reputation: 142008
You need to set up your mock to behave correctly. Something along this lines (note that you can make tests async too):
public class CaseUnitTest
{
[Fact]
public async Task GetCaseByID_ShouldReturnBadRequest_WrongCaseNumber()
{
var casesService = new Mock<ICasesService>();
casesService.Setup(service => service.GetCaseById(It.IsAny<int>()))
.ThrowsAsync(new NullReferenceException(""));
var caseController = new CaseController(casesService.Object);
var result = await caseController.GetCaseById(0);
Assert.IsAssignableFrom<BadRequestObjectResult>(result);
}
}
Some more notes:
NullReferenceException
for GetByID
when case is not found is a quite questionable choice.Upvotes: 1