Checking argument values passed to a constructor

1,018 views
Skip to first unread message

Gabrielius

unread,
Jun 21, 2016, 10:50:36 AM6/21/16
to NSubstitute
Hello all,

It is possible to check what values were passed to a method using Arg.Do<T>. Yet I was wondering, is it possible to do the same thing with constructor? I checked official documentation, yet could not find the answer to my question, neither the examples.

Thanks,
Gabe

David Tchepak

unread,
Jun 21, 2016, 9:07:59 PM6/21/16
to nsubs...@googlegroups.com
Hi Gabe,

No NSubstitute can't do this with constructors. The standard approach I've seen is to use a factory interface or func.

For example:

    var factory = Substitute.For<Func<Arg1, Arg2, MyClass>>();
    ...
    factory.Received().Invoke(expectedArg1, expectedArg2);

    // Or
    var factory = Substitute.For<IMyClassFactory>();
    ...
    factory.Received().Create(expectedArg1, expectedArg2);

This has the downside of making the code a more complex though.

The other thing to consider is that what the object does is probably more important that what it was created with. So rather than testing the object was created with an array of `[10, 20, 30]`, you could assert that `myObj.GetIds()` returns `[10, 20, 30]` instead (i.e. the value it was constructed with results in the correct object behaviour).

Regards,
David

PS: `.Received()` is usually used to check values a method is called with, although sometimes `Arg.Do` is used if you want to do more complex assertions on values (as NSub is currently a bit limited in what it provides there).




--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
To post to this group, send email to nsubs...@googlegroups.com.
Visit this group at https://groups.google.com/group/nsubstitute.
For more options, visit https://groups.google.com/d/optout.

Gabrielius

unread,
Jul 1, 2016, 2:48:30 PM7/1/16
to nsubs...@googlegroups.com
Hey David,

While I knew I could use a factory interface substitute, to use a `Func` was unexpected to me.

Basically, I am trying to mock a very simple class `FtpClient` to be used in a SSIS package test. I need to ensure that SSIS package instantiates `FtpClient` with particular parameters that I pass to SSIS package itself. 

What I ended up with is that initialize the class not through constructor but via `Initialize` method I added to `FtpClient`.

Best regards,
Gabe

P. S. Yes, you are completely right regarding `Received()` method. I was just trying to solve my problem, tried many ways and fixated on `Arg.Do<T>` trying to save a copy of a parameter passed ;)
Reply all
Reply to author
Forward
0 new messages