简体   繁体   中英

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:

  • Create a wrapper class around A and pass it into DoFoo() . The wrapper class distinguishes between the real and the fake implementation.
  • The same could be done using extension methods.
  • Use dynamic and pass in a fake class with an empty DoFoo() implementation.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM