As I showed in the previous post here are the other places where the TypeMock team would have loved to use TypeMock 🙂
Case 2. Mocking another Process.
The Tracer is a class that is used to send and recieve trace messages to the Tracer GUI. Before the tracer pushes a message into the message pipe, it checks if a GUI exists.
private bool ClientIsRunning() { // Code that checks that a Tracer GUI is up and runnning, using inter-process mutex return processFound; } |
In order to test the Tracer we have to fake that the client is running, without having the real GUI. We cannot set the mutex as Windows will not block mutexes in the same process.
Using TypeMock we would do the following:
Mock m = MockManager.Mock(typeof(Tracer)); m.AlwaysReturn(“ClientIsRunning”,true); |
Simple, but we cannot so we did the following:
We changed the signiture of ClientIsRunning to:
protected virtual bool ClientIsRunning |
and created a Mocked Tracer:
public class TestTracerMock : Tracer { protected override bool ClientIsRunning() { return true; } } |
And used a technique to swap the real Tracer with our TestTracerMock. Here is how:
Our tracer is a singleton so that it can be used throught the framework:
internal static Tracer Instance { get { if (tracer==null) { tracer = new Tracer(); } return tracer; } } |
We swap the Tracer by inserting the MockedTracer into the tracer field:
[TestFixtureSetUp] public void ChangeTracer() { TestTracerMock traceMock = new TestTracerMock(); typeof(TypeMock.Tracer).GetField(“tracer”, BindingFlags.NonPublic|BindingFlags.Static) .SetValue(null,traceMock); } |
We had to change the Tracers constructor to public too.
The Author, you – super hero!
http://unikont.com
Well, thanks!
Good aftenoon !
http://assolt.com
Very nicely done forum.
Thanks much!