Bradford Fisher
Bradford Fisher

Reputation: 141

Is there a standard method for unit testing code where dependencies do not implement interfaces?

Is there a standard method for unit testing code where dependencies do not implement interfaces? For instance, the System.Net.Http namespace only exposes concrete classes. If I'm trying to unit test a class which relies upon one of the concrete classes in System.Net.Http, should I merely construct an instance of, say, HttpRequestMessage, set it's properties and then supply this newly constructed object to the system under test? Would it make sense to subclass HttpRequestMessage and have it implement a custom interface which could then be mocked/stubbed?

Upvotes: 3

Views: 382

Answers (3)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

Another good tool for testing legacy code is Typemock

Upvotes: 0

Thai Anh Duc
Thai Anh Duc

Reputation: 524

I would suggest you have a look at: AutoFixture http://autofixture.codeplex.com/ It helps you construct the object in the way you want. In your example, HttpRequestMessage, you can customize the fixture: fixture.Customize<HttpRequestMessage>(c => {}); There are many examples out there using AutoFixture in Unit Testing. Or you can post the code you want to test here and i can try to help.

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

The recommended practice is to wrap this object in a class of your creation, which itself implements an interface. You would then use this wrapper class in your code, and you can then supply mocked versions of this wrapper in place of the real class. You would not subclass it using this method, but rather contain it and use delegation (not to be confused with delegates!) to forward each method.

For instance, you might create a class HttpRequestMessageWrapper that inherits from IHttpRequestMessage (that you define, including all the public properties of HttpRequestMessage.. although you could probably get by with only implementing the properties you use).

Alternatively, you can use a testing framework that supports shims, which is a framework that essentially does this wrapper for you and replaces calls to the objects with shim versions. Microsoft Fakes (introduced in VS 2012 MS Test) does this.

Shims are typically used to replace common framework calls, such as DateTime.Now so you can supply a specific value during tests.

Upvotes: 8

Related Questions