typemock threw InvalidCast exception

64 Views Asked by At

I have following code snipped and I tried to test it using typemock but got InvalidCast exception. ISomeClass is just an interface and SomeClass implements that interface. UseOfSomeClass is another class which uses SomeClass and its constructor takes SomeClass as parameter. I need to test UseOfSomeClass. How do I inject a typemock fake object into a class constructor?

public interface ISomeClass
{
    void DoSomething();
}

public class SomeClass : ISomeClass
{
    public void DoSomething()
    {
        Console.WriteLine("Do something!");
    }
}

public class UseOfSomeClass
{
    public SomeClass SomeClassProperty { get; set; }

    public bool IsChecked { get; set; }

    public UseOfSomeClass(SomeClass someClass)
    {
        SomeClassProperty = someClass;
    }

    public void MyMethod()
    {
        SomeClassProperty.DoSomething();

        IsChecked = true;
    }
}

Then test:

[TestClass]
public class UseOfSomeClassTest
{
    [TestMethod]
    public void TestMethod1()
    {
        var fakeSomeClass = Isolate.Fake.Instance<ISomeClass>();

        var use = new UseOfSomeClass((SomeClass)fakeSomeClass);

        use.MyMethod();

        Assert.IsTrue(use.IsChecked);
    }
}

Thanks!

1

There are 1 best solutions below

0
Sam On

Typemock Isolator allows you to mock concrete classes, so there's no need to fake ISomeClass in your test case. You can just fake SomeClass and send it as a parameter to the ctor.

[TestMethod, Isolated]
public void TestMethod1()
{
    var fakeSomeClass = Isolate.Fake.Instance<SomeClass>();

    var use = new UseOfSomeClass(fakeSomeClass);

    use.MyMethod();

    Assert.IsTrue(use.IsChecked);
}