Search code examples
c#visual-studioexceptionnunitassert

Catch the exception and assert it using C# Nunit


I am doing a negative test and I am expecting to get an exception. So all I want to know is how I can catch the exception's message and then assert it.

[Then(@"I create the (.*)")]
    public void ThenICreateTheContact(string entityName)
    {
        entityId = m_OrgServ.Create(entity);
    }

    [Then(@"I verify the exception")]
    public void ThenIVerifyTheException()
    {
        ScenarioContext.Current.Pending();
    }

and this is the exception -

Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not ExistSystem.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not Exist (Fault Detail is equal to Exception details: 

The exception occurs when I do m_OrgServ.Create(entity); So I want to catch it and then assert its message in the next method that I have shown.


Solution

  • You can use TestDelegate.

        private TestDelegate _create;
        
        [Then(@"I create the (.*)")]
        public void ThenICreateTheContact(string entityName)
        {
            _create = () => m_OrgServ.Create(entity);
        }
    
        [Then(@"I verify the exception")]
        public void ThenIVerifyTheException()
        {
          var exception = Assert.Throws<FaultException<OrganizationServiceFault>>(_create);
          Assert.That(exception.Message, Is.EqualTo("expected message here"));
        }