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 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();