How to use Fluent Assertions to test for exception in inequality tests?

C#Unit TestingLambdaNunitFluent Assertions

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan BieremaView Question on Stackoverflow
Solution 1 - C#KoteView Answer on Stackoverflow