Capturing exceptions with Nunit in .NET

In this tutorial we are going to capture exception that service throw using nUnit test framework. It is quite important writing unit tests or integration tests to be able to specify scenario that will force method to threw an exception so we are prepared for that eventuality.

We are having fruit service that stores info regarding fruit availability in the fridge. 



public class FruitService
  {
    public async Task CheckIfFruitIsInTheFridge(string fruit)
    {
      // To keep it simple call Fridge method. In real environment we would call
      // some external api and we want to create new thread for that.

      var fruitInTheFridge = Fridge(fruit);

      if(fruitInTheFridge == null)
      {
        throw new Exception("Could not find fruit in the fridge."); 
      }

      return await fruitInTheFridge;
    }

    private async Task<string> Fridge(string fruit)
    {
      // Ok beer is not part of the fruit company, but beer must always be in the fridge :)

      List currentfruitsInTheFridge = new List<string> { "Apple", "Pearl", "Beer" };

      return currentfruitsInTheFridge.FirstOrDefault(m => m.Equals(fruit));
    }
  }

Now we are going to run tests.

[TestFixture]
  public class WhenCallingCheckIfFruitIsInTheFridge
  {
    private FruitService _fruitService;

    [SetUp]
    public void SetUp()
    {
      this._fruitService = new FruitService();
    }

    [Test]
    public void ItThrowsAnExceptionWhenfruitIsNotFoundInTheFridge()
    {
      var ex = Assert.ThrowsAsync<exception>(async () => await this._fruitService.CheckIfFruitIsInTheFridge("Grapes"));

      Assert.That(ex.Message, Is.EqualTo("Could not find fruit in the fridge."));
    }
  }

Comments

  1. This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it, Fridge price in Nigeria

    ReplyDelete

Post a Comment