0

I have a class which inherits from WebClient - in some code I am trying to test there is the usual:

using(var client = new SomeWebClient()){...}

Now I don't want to use that SomeWebClient class in my tests so I'd like to inject in some kind of stub.

Without using the servicelocator pattern what are my options? I can't use any real IoC as this assembly is used by multiple platforms both mobile and full .NET

I'm sure the answer is staring me in the face but I think I'm having "one of those days"!

13
  • Can you change the code you want to test? Commented Jun 13, 2013 at 12:54
  • I can but nothing huge
    – user156888
    Commented Jun 13, 2013 at 12:55
  • I'm sorry, I don't quite understand what is preventing you from using a DI framework. Could you elaborate a bit? Commented Jun 13, 2013 at 12:55
  • Create something that inherits from SomeWebClient. Override all the functions there and use this in the test code (just exchange this one line which you have shown). Not perfect, but fulfills the requirements.
    – Michal B.
    Commented Jun 13, 2013 at 12:57
  • 1
    Well, the first requirement for being able to use some kind of stub is to use an abstraction (abstract class or interface) in your using statement instead of var. Then it depends on your project where you get the concrete implementation. You could either pass it to your code as a parameter or use a factory. Commented Jun 13, 2013 at 12:58

2 Answers 2

3

1) Use an interface

using(ISomeWebClientc = new SomeWebClient()){...}

2a) Create a factory that returns an ISomeWebClient implementation.

3) Let it return your correct class in the production code or let it create a stub in your tests.

2b) Alternatively, just pass an ISomeWebClient to your class or method and initialize it differently in your test or production code.

0

You can inject a Func<TResult>. This Func is then called in your using statement, like so:

using (ISomeClient client = InjectedFunc())
{
    ...
}

public delegate Func<ISomeClient> InjectedFunc();

...

Then somewhere in your code you assign this Func a value, which is a code block to be executed later:

InjectedFunc = delegate(){ return new MyImplementation(); };
// or some other way of creating a new instance, as long as
// you return a fresh one

and so, this is functionally the same as if your using block would say:

using (ISomeClient client = new MyImplementation())
{
    ...
}
1
  • Why would you use delegate instead of the more succinct lambda syntax? () => new MyImplementation()
    – svick
    Commented Jun 13, 2013 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.