54

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.

Nathan Bierema
  • 1,813
  • 2
  • 14
  • 24

2 Answers2

87

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();
Kote
  • 2,116
  • 1
  • 19
  • 20
0

you can use Invoking too

 comparison.Invoking(()=> {var res = lhs > rhs;})
.Should().Throw<Exception>();

more information is here

mostafa kazemi
  • 514
  • 6
  • 7