I'm learning how to unit test ASP.NET Core web applications by reading the docs and tutorials, but not progressing too much because the docs looks kinda silly to me. I'm following the right path?
I have this abstract class BaseRepository:
public abstract class BaseRepository<TEntity, TContext>
: IRepository<TEntity>
where TEntity : class, IBaseEntity
where TContext : DbContext
{
protected readonly TContext _context;
protected BaseRepository(TContext context)
{
_context = context;
}
public async Task<TEntity?> GetById(int id)
{
return await _context.Set<TEntity>().FindAsync(id);
}
public async Task<TEntity> Create(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
await _context.SaveChangesAsync();
return entity;
}
}
There is an UserRepository class that inherits from BaseRepository:
public class UserRepository : BaseRepository<User, TodoContext>
{
public UserRepository(TodoContext context) : base(context)
{}
}
And my test:
public class UnitTest1
{
[Fact]
public async Task Test1()
{
var userTestObject = new User
{
Id = 1,
NickName = "johnDoe",
Email = "johndoe@email.com",
Password = "Pass@1234",
UserTasks = new List<UserTask>()
{
new UserTask()
{
Id = 1,
Description = "Study C#/.NET"
}
}
};
var repositoryMock = new Mock<IRepository<User>>();
var contextMock = new Mock<TodoContext>();
repositoryMock.Setup(m => m.Create(It.IsAny<User>()))
.Returns(Task.FromResult(userTestObject));
// Acts
var repository = new UserRepository(contextMock.Object);
await repository.Create(userTestObject);
// Asserts
repositoryMock.Verify(x => x.Create(It.Is<User>(y => y == userTestObject)));
}
}
And the exception is being thrown at this line:
await repository.Create(userTestObject);