Sunday, September 11, 2022

C#: xUnit Testing Constructor Exceptions

xUnit's Assert class implements the following methods that test whether or not a method throws an exception:


 

The Throws method signatures that take a parameter of type Action are used to test methods that return no value (void). The Throws method signatures that take a parameter of type Func are used to test methods that return a value. In order to test a constructor that throws an exception, a lambda expression is required such as:

Assert.Throws<ArgumentException>(
    () => new AnyClass());

Assert.Throws<ArgumentException>(
    () => new AnyClass("some paramter", 123, DateTime.Now));

The lambda expressions above return no values, so the Throws method that takes an Action parameter is invoked by the above code (public static T Throws<T>(Action testCode) where T : Exception).






 




No comments :

Post a Comment