urizark
urizark

Reputation: 138

How to test the logic of a catch block using xUnit

At work I have a function that generically does this:

        public SomeObject MethodWithTryCatch()
        {
            //some logic
            try
            {
                //some logic that may throw an exception
            }
            catch(Exception exception)
            {
                return new SomeObject
                {
                    //list of properties
                    ErrorMessage = exception.Message
                }
            }
        }

I want to test a couple things:

  1. that indeed an exception was caught
  2. and that the returned object is equivalent to the one I expected

Questions:

  1. is it possible to "trip" the method directly into the catch block?
  2. becauseErrorMessage = exception.Message how can I make sure the expected object and actual object will have the same ErrorMessage value?
  3. generally how do you test something like this using xUnit?

Upvotes: 0

Views: 72

Answers (1)

jazb
jazb

Reputation: 5791

Try using Assert.Throws statement to verify the exception is raised.

eg

[Fact]
public void VerifyCatch()
{
   
    var f = new Foo();
   
    var e = Assert.Throws<SomeException>(() => f.MyMethod());
    Assert.Equal("My expected message", e.Message);
}

Upvotes: 1

Related Questions