Reputation: 1933
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.
Upvotes: 64
Views: 80736
Reputation: 575
you can use Invoking too
comparison.Invoking(_ => {var res = lhs > rhs;})
.Should().Throw<Exception>();
more information is here
Upvotes: 3
Reputation: 13198
I think the right way to write this would be something like this:
var value1 = ...;
var value2 = ...;
value1.Invoking(x => x > value2)
.Should().ThrowExactly<MyException>()
.WithMessage(MyException.DefaultMessage);
Upvotes: 2
Reputation: 2266
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();
Upvotes: 101