3

The following Func delegate throws an ArgumentNullException:

Func<Task> act = async () => await _someService
            .someMethod(1, 2, 3, 4);

Using Fluent assertions, the assertion:

act.Should().ThrowExactlyAsync<ArgumentException>();

Should fail:

Asserts that the current Func throws an exception of the exact type TException (and not a derived exception type).

ArgumentNullException derives from ArgumentException, given the description, the assertion should fail, but it passes.

Is it a bug or am I misusing this?

anastaciu
  • 23,467
  • 7
  • 28
  • 53

2 Answers2

7

Since ThrowExactlyAsync returns a Task, you're not actually doing anything unless you await it:

await act.Should().ThrowExactlyAsync<ArgumentException>();
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • On further checks I found that `act` is `System.Func'1[[System.Threading.Tasks.Task, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral...]]` how is this the same as an `ArgumentException`? I mean, how can it pass the test? Thanks for the answer btw. – anastaciu Nov 17 '21 at 15:26
  • It passes because no test/assertion is actually being executed. It's a Task, basically a promise to run the assertion. BTW thanks for the accept, that put me over 100k rep finally haha – DavidG Nov 17 '21 at 15:29
  • I see, makes sense. Well, it's the correct answer, so, you have no one but yourself to blame for this :D I'm glad I was the one to push you through, though. – anastaciu Nov 17 '21 at 15:32
0

Replace act.Should().ThrowExactlyAsync<ArgumentException>();
with await act.Should().ThrowExactlyAsync<ArgumentException>();\

This will give you a correct result (fail in this case).

quain
  • 861
  • 5
  • 18