Marcel Bonzelet
Marcel Bonzelet

Reputation: 238

Replace implementation of a "sealed" class

A is a class from a referenced dll and thus cannot be changed. It has a method Foo() that is called inside my DoFoo() method (taking A as a parameter). I want to test DoFoo() without executing Foo() because it's expensive and already tested.

What's best practice to do in such a situation?

My thoughts on this:

Upvotes: 2

Views: 2555

Answers (2)

JamesR
JamesR

Reputation: 745

Actually it's very easy doing it with Typemock, you wont need to use wrapper or create interfaces, you can just mock it. For example:

method under test:

public string DoFoo(A a)
    {
        string result = a.Foo();
        return result;
    }
}

sealed public class A
{
    public string Foo()
    {
        throw new NotImplementedException();
    }
}

Test:

[TestMethod,Isolated]
public void TestMethod1()
{
    var a = Isolate.Fake.Instance<A>(Members.CallOriginal);

    Isolate.WhenCalled(() => a.Foo()).WillReturn("TestWorked");

    var classUnderTest = new Class1();
    var result = classUnderTest.DoFoo(a);

    Assert.AreEqual("TestWorked", result);
}

Upvotes: 1

L-Four
L-Four

Reputation: 13531

Create an interface that contains the methods you want to expose.

Create a wrapper class that implements that interface and which uses the external assembly's classes to do its work. You can create other implementations of this interface, like a mock implementation.

Inject the interface with constructor injection for example, into the classes where you need the functionality.

In your test you can then easily replace the implementation that uses the external library with your mock implementation.

Upvotes: 3

Related Questions