Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 898
Nathan Bierema Avatar asked Jan 26 '16 03:01

Nathan Bierema


People also ask

How do you add fluent assertions to a project?

You can search for that in the Nuget Package Manager and install it in the test project. Out-of-the box, Fluent Assertions provides tons of extension methods that help to easily write assertions on the actual as shown below. In the following example, I will run the test against one sample string of my name.

Why use FluentAssertions?

FluentAssertions provides better failure messages Ideally, you'd be able to understand why a test failed just by looking at the failure message and then quickly fix the problem. This is one of the key benefits of using FluentAssertions: it shows much better failure messages compared to the built-in assertions.

What is assertion scope?

Assertion Scopes make our lives easier when using multiple assertions within our unit tests by saving us time and effort when finding out why our tests are failing. Assertion Scopes allow us to test multiple assertions within a single test execution.


1 Answers

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(); 
like image 161
Kote Avatar answered Oct 06 '22 01:10

Kote