chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!
0 votes
How to fake methods of generic class?
asked by (2.1k points)

1 Answer

0 votes
To fake a generic class, we will use the Isolate.Fake.Instance API, and set the class name, for example:
Isolate.Fake.Instance<GenericClass<int>> ();


In this example, we will set a behavior of 3 methods: public, private and static.


public class GenericClass<T>
{

    public string PublicMethod()
    {
      return " ";
    }

    private string PrivateMethod()
    {
      return " ";
    }

    public string CallPrivateMethod()
    {
      return this.PrivateMethod();
    }
    
    public static string StaticMethod()
    {
      return " ";
    }

}


Public Method:

  [TestMethod]
  public void FakingPublicMethod()
  {
    var example = Isolate.Fake.Instance<GenericClass<int>>();

    Isolate.WhenCalled(() => example.PublicMethod()).WillReturn("I'm a fake PublicMethod");

    var expectedString = "I'm a fake PublicMethod";
    var actualString = example.PublicMethod();

    Assert.AreEqual(expectedString, actualString);
  }



Private Method:

In order to fake a private method we will use the isolate.NonPublic.WhenCalled API.
  [TestMethod]
  public void FakingPrivateMethod()
  {
    var example = new GenericClass<int>();

    Isolate.NonPublic.WhenCalled(example, "PrivateMethod").WillReturn("I'm a fake PrivateMethod");

    var expectedString = "I'm a fake PrivateMethod";
    var actualString = example.CallPrivateMethod();

    Assert.AreEqual(expectedString, actualString);
  }



Static Method:
When faking a static method, we will use the Isolate.Fake.StaticMethods API:
Isolate.Fake.StaticMethods<GenericClass<int>>().

to set a behavior on a ststic method (WhenCalled), we don't need an instance, just the name of the class.


  [TestMethod]
  public void FakingStaticMethod()
  {
    Isolate.Fake.StaticMethods<GenericClass<int>>();  //default for all static menthods

    Isolate.WhenCalled(() => GenericClass<int>.StaticMethod()).CallOriginal();

    var expectedString = "I'm in StaticMethod";
    var actualString = GenericClass<int>.StaticMethod();

    Assert.AreEqual(expectedString, actualString);

  }
answered by (4k points)
...