I am trying to test ASP.NET Core Web API controllers using XUnit. I am using the DBContext directly in the controller. In production, I am using SqlServer and for testing, I am using InMemory provider. When I am testing some code which is using the EF Core FirstOrDefaultAsync
method, the application is throwing null reference exception. The value I am looking for doesn't exist in the DB. As per my understanding, it should return NULL, it should not throw an exception.
I tried something like where(x => x.Id = id).FirstOrDefaultAsync()
, it is also throwing the same null reference exception.
When I tried something like
var exist = await list.AnyAsync(x => x.Id == id);
if(!exist)
{
return NotFound();
}
var user = await list.FirstAsync(x => x.Id == id);
return user;
It works. Both dbcontext and users property are got values, those are not null.
Please help.