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

3

60

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.

Mariande answered 26/1, 2016 at 3:10 Comment(2)
See fluentassertions.com/documentation/#exceptionsTriaxial
That link is already dead. Right now it's changed to fluentassertions.com/exceptions but Kote's answer should steer anyone coming later correctly.Powdery
H
98

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();
Hanhana answered 26/1, 2016 at 4:6 Comment(2)
act.Should().NotThrow(); to check for not exceptions.Faulkner
I used it slightly different for my problem because I was testing an async method. So for async/await you can replace Action to Func<Task>Moo
W
3

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);
Wiggler answered 18/10, 2023 at 23:12 Comment(0)
B
2

you can use Invoking too

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

more information is here

Banshee answered 22/7, 2022 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.