0

I am new to unit testing and I have been using the CQRS mediatR pattern. I want to add unit tests for GetAllAsync() and GetByGameNameAsync() methods using Moq and xUnit. The code runs fine as intended but I need unit testing for it.

There is no connected database, I need to be able to write tests that will check both GetAllAsync() and GetByGameNameAsync() methods to see if it is working as intended.

How can i use inmemoryDb to write tests for the two methods?

public class IGenericRepository<TContext, TEntity> : IGenericRepository<TEntity>

 where TContext: DbContext
where TEntity: class
{
private readonly TContext _gameDbContext;

private readonly DbSet<TEntity> _gameDbSet;

public IGenericRepository(TContext dbContext)
{
_gameDbContext = dbContext;
_gameDbSet = dbContext.Set<TEntity>();
}

public async Task<IReadOnlyList<TEntity>> GetAllAsync()
{
var getBack = await _gameDbSet.ToListAsync();
return getBack;
}

GameDbContext.cs

public class GamesDbContext : DbContext
{
public GameDbContext(DbContextOptions<GamesDbContext> options) :base(options)
{
}
public DbSet<GamesEntity> GamesEntity => Set<GamesEntity>():

GamesEntity.cs

public int Id {get; set;}
public string gameName {get; set;} =null!;
public string gameDescription {get; set;}=null!;

GamesRepository.cs

public class GamesRepository: GenericRepository<GamesDbContext, GamesEntity>, IGamesRepository
{
private readonly GamesDbContext _gamesDbContext;
private readomly GamesDbSet<GamesEntity> _gamesDbSet;

public GamesRepository( GamesDbContext dbContext) : base(dbContext)
{
_gamesDbContext - dbContext;
_gamesDbSet = dbContext.Set<GamesEntity>();
}

public async Task<ReadOnlyList<GamesEntity>> GetByGameNameAsync(string gameName)
{
var gameEntities = await _gamesDbContext.GamesEntity.
                     Where(v => v.Entity == gameName)
                      .ToListAsync();

return gameEntities;
}
LowKeyLo
  • 57
  • 8

1 Answers1

0

With such an organization of the code, there is no way to make unit tests, since mocking DbContext is a practically impossible and, most importantly, useless task.

The repository itself does not contain complex business logic, and covering it with tests does not bring any benefit.

If you still need to write tests, then you can use In-Memory DB, although there are many opponents of this approach.

asku
  • 71
  • 2