2

I am new to NSubstitute and 30 minutes in I can't find how to mock class level fields / variables.

In MOQ I would do this:

public class PlanControllerTest
{

    Mock<IDataAccessTemplate> _template = new Mock<IDataAccessTemplate>();

    [TestMethod]
    public void BadDataResponse()
    {
       Mock<ISomethingElse> other = new Mock<ISomethingElse>();

    }

}

However refactoring to NSubstitute I use:

public class PlanControllerTest
{

    ???? _template = Substitute.For<IDataAccessTemplate>();

    [TestMethod]
    public void BadDataResponse()
    {
       var other = new Substitute.For<ISomethingElse>();

    }

}

It is that class level declaration that I can't figure out. I've been through the basic tutorial here:

http://nsubstitute.github.io/help/creating-a-substitute/

and the closest I find via Google is:

How to set value to a local variable of a class using NSubstitute in TestProject?

Surely this is not the first time this has been asked??

Community
  • 1
  • 1
GPGVM
  • 5,515
  • 10
  • 56
  • 97
  • Using the dynamic keyword is an option. Visual Studio should you give a clue of the return type. – Jeroen Heier Jun 09 '16 at 18:27
  • If the docs were updated to `ISomeInterface substitute = Substitute.For()` would that help? My only reservation for that is that `var` seems to be the most common way this is written in C#, and maybe the docs should reflect that? – David Tchepak Jun 10 '16 at 00:49

1 Answers1

1

See the NSubstitute code. The implementation of For <T> will return T. So using IDataAccessTemplate should compile.

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32