NSubstitute.Analyzers icon indicating copy to clipboard operation
NSubstitute.Analyzers copied to clipboard

NS2002 falsely triggered by optional ctor args

Open lonix1 opened this issue 4 years ago • 5 comments

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 avatar Nov 17 '21 15:11 lonix1

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?

lonix1 avatar Nov 17 '21 16:11 lonix1

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?

tpodolak avatar Nov 17 '21 16:11 tpodolak

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.

lonix1 avatar Nov 17 '21 16:11 lonix1

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?).

dtchepak avatar Nov 18 '21 00:11 dtchepak

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

tpodolak avatar May 04 '22 23:05 tpodolak