title: Unit testing a Web API controller
body: <p>I am fairly new to unit testing and I am trying to create a unit test for a Web API contoller that I have created which returns a list of brands.</p>
  
  <p>My Web API controller <code>Get()</code> method looks like this:</p>
  
  <pre><code>[HttpGet("/api/Brands/Get", Name = "GetBrands")]
  public async Task&lt;IActionResult&gt; Get()
  {
      var brands = await _brandsService.GetAll(null, "Image");
      return Json(brands);
  }
  </code></pre>
  
  <p>The generic service method looks like this:</p>
  
  <pre><code>public async Task&lt;List&lt;T&gt;&gt; GetAll(
      Func&lt;IQueryable&lt;T&gt;, 
      IOrderedQueryable&lt;T&gt;&gt; orderBy = null, 
      string includeProperties = null)
  {
      return await _genericRepository.GetAll(orderBy, includeProperties);
  }
  </code></pre>
  
  <p>and the generic repo method looks like this:</p>
  
  <pre><code>public async Task&lt;T&gt; Get&lt;TKey&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; filter = null, string includeProperties = "", bool noTracking = false)
  
  {
      includeProperties = includeProperties.Trim() ?? string.Empty;
      IQueryable&lt;T&gt; query = Context.Set&lt;T&gt;();
  
      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();
  }
  </code></pre>
  
  <p>This is working and I am returning a list of brands from the database.</p>
  
  <p>Now I tried to create a Unit test for this:</p>
  
  <pre><code>[SetUp]
  public void Setup()
  {
      Brands = new List&lt;Brand&gt;
      {
          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()
  {
      //Arrange
      var mockService = new Mock&lt;IGenericService&lt;Brand&gt;&gt;();
      mockService.Setup(repo =&gt; repo.GetAll(null, null)).Returns(Task.FromResult(Brands));
      var controller = new BrandsController(mockService.Object);
  
      //Act
      var result = await controller.Get();
      //Assert
  }
  </code></pre>
  
  <p>however the result is always null.  Am I testing this correctly or do I need to change my unit test code to verify that the mock service has three items stored?</p>