Skip to content

Unexpected assertion issue #2679

@ddotlic

Description

@ddotlic

Hi,

first of all, thanks for your hard work, the library is a breath of fresh air in the .NET testing ecosystem!

I've encountered an issue which I'm not sure could be solved via an extension and it potentially shows a slightly bigger shortcoming, unless I missed something obvious.

I use a 3rd party package which gives me a Func<int>?, let's call the variable main.

When I try to assert that the value is not null, I do it like this

Assert.That(main).IsNotNull()

This does not compile because of the available overrides, there's only one for Func<T>, none for Func<T>?.

By itself, not a huge deal, since I can always do main?.Invoke() and then assert that the result of that is not null; that works. The alternative where I use main! in hundreds of my tests seems... dirty, for the lack of the better word 😉

I wonder if something can be done about this and/or if the extension system is enough to make this work?

The second shortcoming is IMO more interesting: in a general case, when an API returns nullable reference type, after we've asserted that it is not null, the compiler should see the reference in the following lines as no more potentially null.

IOW, if I have the following example:

T? something = someApiCall();
Assert.That(something).IsNotNull();
something.MethodCall();

(assuming T is class and does have a MethodCall method)

The compiler is not aware that on the line 3 - and onward! - the something can be narrowed to T.

When I used xUnit prior, a similar scenario worked as expected:

T? something = someApiCall();
Assert.NotNull(something);
something.MethodCall();

There are no warnings for the lines following the assert; if we remove/comment out the assert, the compiler produces Warning CS8602 : Dereference of a possibly null reference. which is always produced in the TUnit example, with or without the IsNotNull assertion.

Supposedly this is because in xUnit NotNull()'s parameter - thing we're asserting on - is marked with the [NotNull] attribute, which admittedly is (maybe) a challenge for TUnit because IsNotNull() does not have parameters (but I do admit I have not looked deep enough into the assertion framework architecture).

Any advice or guidance is very much appreciated.

Keep up the good work!

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions