I'm trying to write a unit test for a greater than overridden operator using Fluent Assertions in C#. The greater than operator in this class is supposed to throw an exception if either of the objects are null.
Usually when using Fluent Assertions, I would use a lambda expression to put the method into an action. I would then run the action and use action.ShouldThrow<Exception>
. However, I can't figure out how to put an operator into a lambda expression.
I would rather not use NUnit's Assert.Throws()
, the Throws
Constraint, or the [ExpectedException]
attribute for consistencies sake.
You can search for that in the Nuget Package Manager and install it in the test project. Out-of-the box, Fluent Assertions provides tons of extension methods that help to easily write assertions on the actual as shown below. In the following example, I will run the test against one sample string of my name.
FluentAssertions provides better failure messages Ideally, you'd be able to understand why a test failed just by looking at the failure message and then quickly fix the problem. This is one of the key benefits of using FluentAssertions: it shows much better failure messages compared to the built-in assertions.
Assertion Scopes make our lives easier when using multiple assertions within our unit tests by saving us time and effort when finding out why our tests are failing. Assertion Scopes allow us to test multiple assertions within a single test execution.
You may try this approach.
[Test] public void GreaterThan_NullAsRhs_ThrowsException() { var lhs = new ClassWithOverriddenOperator(); var rhs = (ClassWithOverriddenOperator) null; Action comparison = () => { var res = lhs > rhs; }; comparison.Should().Throw<Exception>(); }
It doesn't look neat enough. But it works.
Or in two lines
Func<bool> compare = () => lhs > rhs; Action act = () => compare();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With