I am trying to test an ASP.NET Core API controller using an InMemory database, instead of a SQL server. I am also using NUnit to write my tests. In my SetUp-method, I create some data and add to my InMemory context, which seems to work fine, but when I try to retrieve the data using my controller, I get null values.
This is part of my controller:
public class PeopleController : ControllerBase
{
private ApplicationDbContext _context;
private IMapper _mapper;
public PeopleController(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
// GET /api/people
[HttpGet]
public IActionResult GetPeople()
{
return Ok(_context.People.ToList().Select(_mapper.Map<Person, PersonDto>));
}
}
And below is part of my test class. When I debug the test, the two Person objects I add to _context have been added correctly, but when I call _controller.GetPeople(), the two objects do not show up, but I get null back. The method works fine "live", using my SQL Server.
[TestFixture]
class PeopleControllerTests
{
private ApplicationDbContext _context;
private IMapper _mapper;
private PeopleController _controller;
[SetUp]
public void SetUp()
{
_mapper = GenerateConcreteInstance();
var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseInMemoryDatabase(databaseName: "TestDb").Options;
_context = new ApplicationDbContext(options);
_context.People.Add(new Person()
{ Id = 1, Firstname = "XXXXX", Lastname = "XXXXXXX", Email = "XXXX@XXXX.com", City = "XXXXX", DateCreated = DateTime.Now });
_context.People.Add(new Person()
{ Id = 2, Firstname = "YYYYY", Lastname = "YYYYYYY", Email = "YYYY@YYYY.com", City = "YYYYY", DateCreated = DateTime.Now });
_controller = new PeopleController(_context, _mapper);
}
[Test]
public void GetAll_WhenCalled_ReturnPeopleInDb()
{
var result = _controller.GetPeople();
var okObjectResult = result as OkObjectResult;
var content = okObjectResult.Value as IEnumerable<Person>;
Assert.IsNotNull(content);
}
private IMapper GenerateConcreteInstance()
{
var config = new AutoMapper.MapperConfiguration(c =>
{
c.AddProfile(new ApplicationProfile());
});
return config.CreateMapper();
}
}
Would really appreciate any help, as I am new to ASP.NET Core and testing in general!
Aucun commentaire:
Enregistrer un commentaire