How does "Typemock Isolator" mock static methods?
Asked Answered
I

1

11

As some of you will know, it is generally not possible to mock a static method in .net.

By mocking, I mean to replace a method in a class with another method with the same signature, usually for testing purposes.

The two main methods used for mocking a method are to declare it virtual or define it in an interface. Neither of these two are allowed for .net static methods.

However, there is an expensive tool called "Typemock Isolator" which allows for mocking of static methods. How does Isolator accomplish this seemingly impossible feat?

Immortelle answered 8/7, 2010 at 19:6 Comment(1)
It is outdated info - github.com/Serg046/AutoFakeAgnew
T
10

It's in the FAQ.

Basically, a Typemock fake instantiates a new object of the original type and hooks into each and every method and property call for that object, redirecting the call to the fake and returning the values you specify. It uses some deep voodoo in the .NET Framework (the .NET Profiler API, if you're interested) to do this, but it's all "legit". Technically anyone can build a duplicate of Typemock, but I have yet to see one.

Tamah answered 8/7, 2010 at 19:12 Comment(4)
It says on the web site, "Typemock Isolator uses aspect-oriented technology to redirect calls from the real code. This enables developers to define the behavior of the external component required for a tested scenario." I was hoping to be able to know more about how that happens. I've heard of Aspect-Oriented "post-compiler" tools like PostSharp.Immortelle
@Rising Star: Sorry, I've edited to add more info. PostSharp actually modifies compiled code. Typemock uses the .NET Profiler API to actually intercept method calls as they're being called and redirect them to the fake.Tamah
ACCEPTED: .net profiler api. Does it say somewhere else on their web page that they use the .net profiler api, or do you know some other way?Immortelle
@Rising Star: it's on the FAQ, which I linked in my answer. Internally, it usesthe .NET framework profiler API to monitor an application's execution. When a method is called, the CLR notifies Typemock Isolator; the framework can then return mocked values and override the original code completely.Tamah

© 2022 - 2024 — McMap. All rights reserved.