I am new to unit testing and am trying to create a unit test for the Web API controller I created that returns a list of brands.
My Web API controller's Get()
method looks like this:
[HttpGet("/api/Brands/Get", Name = "GetBrands")] public async Task<IActionResult> Get() { var brands = await _brandsService.GetAll(null, "Image"); return Json(brands); }
The general service method is as follows:
public async Task<List<T>> GetAll( Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null) { return await _genericRepository.GetAll(orderBy, includeProperties); }
and the universal repo method looks like this:
public async Task<T> Get<TKey>(Expression<Func<T, bool>> filter = null, string includeProperties = "", bool noTracking = false) { includeProperties = includeProperties.Trim() ?? string.Empty; IQueryable<T> query = Context.Set<T>(); if (noTracking) { query.AsNoTracking(); } if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } return await query.SingleOrDefaultAsync(); }
This works, and I am returning a list of brands from the database.
Now I tried to create a unit test for this:
[SetUp] public void Setup() { Brands = new List<Brand> { new Brand { Id = 1, Name = "Adidas", ImageId = 1 }, new Brand { Id = 2, Name = "Nike", ImageId = 2 }, new Brand { Id = 3, Name = "Puma", ImageId = 3 } }; } [Test] public async Task Get_ReturnsAAListOfBrands() {
however, the result is always zero. Am I testing this correctly or do I need to change the unit test code to make sure that three elements are stored in the service layout?