title: Asp.Net Core Unit Testing Delete Method in controller
body: <p>I'm unit testing controller logic in a asp.net core project with xUnit and Moq, and I'm having trouble with testing the delete method. I have tried to put together some ideas from different tutorials etc. but still struggling. </p>
  
  <p>I have managed to test that the method returns NoContentResult, and the NotFoundResponse. What I am missing here is the test to see that the delete method actually has deleted an item from the Bygg Repository.</p>
  
  <p>What I am trying to do here in this case is to retreive the list of Bygg, delete an item, and then use assert to check if the list now only contains 2 items. </p>
  
  <p>fyi: bygg = building.</p>
  
  <p>The project follows a repository pattern with generic and userspecific repositories. </p>
  
  <p>This is the delete method in the controller:</p>
  
  <pre><code>[HttpDelete("{id}")]
  public async Task&lt;IActionResult&gt; DeleteBygg(int id)
  {
      try
      {
          var bygg = await _byggRepository.GetByggByIdAsync(id);
          if (bygg == null)
          {
              return NotFound();
          }
  
          await _byggRepository.DeleteByggAsync(bygg);
  
          return NoContent();
      }
      catch (Exception ex)
      {
          return StatusCode(500, "Internal Server Error");
      }
  }
  </code></pre>
  
  <p>This is the test method:</p>
  
  <pre><code>[Fact]
  public async Task DeleteBygg_ExistingIdPassed_RemovesOneItem()
  {
      // Arrange
      _mockRepo.Setup(repo =&gt; repo.DeleteByggAsync(It.IsAny&lt;Bygg&gt;()));
      _mockRepo.Setup(repo =&gt; repo.GetAllByggAsync())
          .ReturnsAsync(GetTestBygg());
  
      // Act
      var actual = await _controller.GetAllBygg();
      var actual2 = actual as OkObjectResult;
      var noContentResponse = await _controller.DeleteBygg(1);
  
  
      // Assert
      var items = Assert.IsType&lt;List&lt;Bygg&gt;&gt;(actual2.Value);
      Assert.Equal(2, items.Count);
  }
  </code></pre>