I have a model in Entity Framework. I want to make sure that Application Service is reading the Generic Repository pointing to the database correctly. How would I test this in Xunit, I am kind of stuck ? Receiving the error below, maybe I need to rewrite code. Need to validate that App service can read example data row below in InMemorydatabase.
Model:
public partial class Department
{
public int DepartmentId { get; set; }
public string DepartmentCode { get; set; }
public string DepartmentName { get; set; }
.... plus additional
}
DTO:
public class DepartmentDto
{
public int DepartmentId { get; set; }
public string DepartmentCode { get; set; }
public string DepartmentName { get; set; }
}
Base Repository from IRepository:
public async Task<T> GetAsync(int id)
{
return await Table.FindAsync(id);
}
**Constructor:**
public BaseRepository(DbContext context)
{
_context = context;
Table = _context.Set<T>();
}
Service: DepartmentAppService.cs
public async Task<DepartmentDto> GetDepartmentById(int id)
{
var department = await departmentRepository.GetAsync(id);
var departmentDto = mapper.Map<Department, DepartmentDto>(department);
return departmentDto;
}
**Constructor:**
public DepartmentAppService(IRepository<Department> departmentRepository, IMapper mapper)
{
this.departmentRepository = departmentRepository;
this.mapper = mapper;
}
Attempted Test Code:
public async Task Get_DepartmentById_Are_Equal()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
var context = new TestContext(options);
Mock<IRepository<Department>> departmentRepositoryMock = new Mock<IRepository<Department>>();
Mock<IMapper> mapperMock = new Mock<IMapper>();
Mock<DepartmentAppService> departmentAppServiceMock = new Mock<DepartmentAppService>(departmentRepositoryMock, mapperMock);
context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
var test = await departmentAppServiceMock.GetDepartmentById(5);
Assert.Equal("123", test.DepartmentCode);
Receiving Error: How to Fix?
'Mock<DepartmentAppService>' does not contain a definition for 'GetDepartmentById' and no accessible extension method 'GetDepartmentById' accepting a first argument of type 'Mock<DepartmentAppService>' could be found (are you missing a using directive or an assembly reference?)
Also have dependency injection in the program. Open to code being rewritten as required,