nsubstitute / NSubstitute.Analyzers

Roslyn analysers for NSubstitute.
MIT License
30 stars 7 forks source link

NS2002 falsely triggered by optional ctor args #176

Open lonix1 opened 2 years ago

lonix1 commented 2 years ago

NS2002 / Constructor parameters count mismatch

Here's a type:

public class Something {
  public Something(string? foo = "foo", int? bar = 10) {
    // etc.
  }
}

This triggers the analyzer:

Substitute.ForPartsOf<Foo>()

Those ctor args are optional.

lonix1 commented 2 years ago

Actually, I'm unsure of this.

Forgetting about the analyser for now (I just disabled it), I nonetheless get this exception;

Exception thrown: 'Castle.DynamicProxy.InvalidProxyConstructorArgumentsException' in Castle.Core.dll

Weird, those args are optional, I'd have thought this would work?

tpodolak commented 2 years ago

Hi @lonix1. As you've seen Castle.Core throws exception even though parameters are options, that is why NSubstitute.Analyzers reports warning. Perhaps we should change warning message to sth more self explanatory. @dtchepak any thoughts on that?

Weird, those args are optional, I'd have thought this would work?

I assume this is limitation of Catle.Core rather than issue with NSubstitute itself, however I dont know that much about internals of NSubstitute. @dtchepak do you maybe know if this is this known problem of Castle.Core?

lonix1 commented 2 years ago

Your idea of a more descriptive warning is good. It will let the user know that it is "normal" and there is nothing he can do about it.

dtchepak commented 2 years ago

IIRC optional arguments are injected at compile-time? In that case Castle.Core will have no way of knowing what to pass to the constructor. (see also this thread).

Does Roslyn provide access to optional param information? If so maybe that should be a new error explaining optional parameters must be passed explicitly (possibly quick fix to pass the defaults?).

tpodolak commented 2 years ago

Does Roslyn provide access to optional param information? If so maybe that should be a new error explaining optional parameters must be passed explicitly (possibly quick fix to pass the defaults?).

Yes, we can extract default values with Roslyn image

I will try to figure out how to use it in ctor matching logic