chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
I can not understand why compiler is keeps telling me type or namespace name needed. I am passing a type to Instance<> ?

//from Reflection namespace
PropertyInfo propertyInfo = ...
Isolate.Fake.Instance<propertyInfo.PropertyType>();


Not even a runtime error, I can't even build, which makes me feel worse I can't figure out the error. Any help on this?
asked by Rybolt (3k points)

3 Answers

0 votes
Unfortunately what you're trying to do is not possible in C#. Instance<>() is a generic method expecting a statically (i.e. compile-time) known type.

Therefore this is not valid:

Type type = name.GetType();
Isolate.Fake.Instance<type>()


Also, PropertyInfo, or any other Reflection type belongs to mscorlib. It's currently not possible to fake mscorlib types.

Perhaps you could refactor your reflection-related logic into a method, and fake that.
answered by igal (5.7k points)
0 votes
Thank you for the useful information, wish the compiler could have said that.

Do you know of any way to set all public properties (reflection or not) with fakes ?

//psuedo code:

var sut = new Foo();

foreach property p in sut.GetProperties()
if p.SetterMethod != null
  p.SetterMethod.Invoke(new Fake(p.Type);
end foreach
answered by Rybolt (3k points)
0 votes
While it's technically possible do do that using our NonPublic API, might I suggest a different approach?

By default, every fake type that is created using Isolator's AAA api is "recursive", meaning, all methods and properties are fakes. You can use the following to have the fake object call an original method:

Isolate.WhenCalled(() => fake.GetSomething()).CallOriginal()


In your case, if your SUT (Foo) has a dependency on Bar, I suggest faking it using the following API:

Isolate.Swap.NextInstance<Bar>().WithRecursiveFake();
var sut = new Foo(); // all calls to Bar are now faked
...


or if you need to set a certain behavior on Bar:

var fakeBar = Isolate.Fake.Instance<Bar>();
Isolate.WhenCalled(() => fakeBar.IsBaz).WillReturn(true);
Isolate.Swap.NextInstance<Bar>().With(fakeBar);

var sut = new Foo();
...
answered by igal (5.7k points)
...