Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FakeItEasy Create a Fake of a Class

I was attempting to use FakeItEasy recently but I wasn't able to create a Fake from a concrete class without working around many quirks.

I tried the following:

public class MyObject {
public MyObject(){}
}
...
MyObject fakeObject = A.Fake<MyObject>();

Which resulted in the a Constructor Not Found with Matching Arguements Exception

Next I tried:

public class MyObject {
public MyObject(string temp){}
}
...
MyObject fakeObject = A.Fake<MyObject>(x => x.WithArgumentsForConstructor(() => new MyObject("temp")));

Which resulted in a similar error.

Finally I tried:

public class MyObject {
//public MyObject(){}
}
...
MyObject fakeObject = A.Fake<MyObject>();

Which allowed me to finally create the fake. I'm confused as to why most of the examples of faking a concrete class allude this is easier that I've found it to be? And why using the documented method, trial #2 above, didn't work?

Are there some limitations to faking a concrete class that aren't documented?

like image 796
Aj-itator Avatar asked Oct 24 '22 21:10

Aj-itator


1 Answers

I recognize this is an old question, so I'm posting this answer for anyone else who has this issue and stumbles into this question. I was able to replicate a similar issue to this.

I have a class:

public class Service : IService
{
   public Service (int prNum)
   {
   //call to a c++ wrapper class (this is where the problem occurs)
   //some other calls
   }
}

I was trying to create the service class as a fake for a unit test:

private Service fakeServ = A.Fake<Service>((x => x.WithArgumentsForConstructor(() => new Service(3))));

I was receiving the same error: Constructor Not Found with Matching Arguments Exception

Eventually I stepped into the A.Fake call with the debugger and found the code inside the constructor (that A.Fake did call) was failing to initialize a block of global memory due to Visual Studio not running in administrator mode. (CreateFileMapping, error code 5, System Error 0x5: CreateFileMapping())

I set visual Studio to run as administrator and the issue was resolved, the fake created.

It seems the Fake, created with a constructor with parameters, does run through the constructor (which is what I was hoping to avoid by creating a fake as the global memory is not part of the focus of my unit test, I'll have to look into if there is a different way I should be creating this).

The code you posted does not indicate you are calling wrapper classes or creating global memory, but you could try stepping into the Fake creation call with the debugger to see if the constructor begins to run and if there is a failure in the constructor, and what errors are returned.

like image 110
xgo Avatar answered Nov 15 '22 11:11

xgo