0

Am having a little trouble understanding what and what cannot be done using FakeItEasy. Suppose I have a class

public class ToBeTested{

   public bool MethodToBeTested(){
      SomeDependentClass dependentClass = new SomeDependentClass();
      var result = dependentClass.DoSomething();
      if(result) return "Something was true";
      return "Something was false";
   }
 }

And I do something like below to fake the dependent class

 var fakedDepClass = A.Fake<DependentClass>();
 A.CallTo(fakedDepClass).WithReturnType<bool>().Returns(true);

How can i use this fakedDepClass when am testing MethodToBeTested. If DependentClass was passed as argument, then I can pass my fakedDepClass, but in my case it is not (also this is legacy code that I dont control).

Any ideas?

Thanks K

Karthik Balasubramanian
  • 1,127
  • 4
  • 13
  • 36

1 Answers1

1

Calling new SomeDependentClass() inside MethodToBeTested means that you get a concrete actual SomeDependentClass instance. It's not a fake, and cannot be a FakeItEasy fake.

You have to be able to inject the fake class into the code to be tested, either (as you say) via an argument to MethodToBeTested or perhaps through one of ToBeTested's constructors or properties.

If you can't do that, FakeItEasy will not be able to help you.

If you do not have the ability to change ToBeTested (and I'd ask why you're writing tests for it, but that's an aside), you may need to go with another isolation framework. I have used TypeMock Isolator for just the sort of situation you describe, and it did a good job.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
  • Like I said before, am trying to write some tests around legacy code, I dont have the luxury of changing the SUT's. I did take a look at TypeMock and it does give me the ability to Fake all instances of a particular class (I tested it and it works just fine). Thanks for your response. – Karthik Balasubramanian Feb 26 '15 at 18:42
  • @KarthikBalasubramanian why can't you change the legacy code? – Adam Ralph Mar 01 '15 at 08:40
  • legacy code is in production being used by a ton of other applications. Currently there are no tests written against it. – Karthik Balasubramanian Mar 01 '15 at 17:51