Thursday, July 17, 2008

Automating the Debug Process

I'm currently listening to Software Engineering Radio podcast. At episode 101 there's a very good interview with

Andreas Zeller on debugging software.

 

The podcast present the problem that debugging manually (the most common debug strategy) is highly inefficient.

Part of the interview is a description of Andreas "Delta Debugging" - By iterative elimination of irrelevant information at the input of the failed test Delta Debugging is able to find and isolates the reason the test failed.

image 

It seems to me that the conclusion from the podcast is that we should aspire for two things in our tests and during debug - automation and understanding of problems when tests fail. And then it hit me - that is exactly what we try to do by using TDD!

 

In TDD instead of taking a big test and eliminate parts of it until we find the cause of the bug we write small isolated unit tests. When a bug introduced to our code we can find and fix it quickly.

And so Mocks and unit tests we can improve (if not solve completely) on the time it take us to find and fix bug in our code.

Don't Sleep

Have you programmed a multi-threaded application?

How many times have you wrote the following lines:

Thread t1 = new Thread(() => Console.WriteLine("Thread 1 working"));

 

t1.Start();

// do some work

Thread.Sleep(5000);

 

// continue execution

or this code snippet:

while (someArgument == true)

{

    Thread.Sleep(10);

}

 

If never - good for you!

The problem is that many programmers when confronted with the need to sync actions in different threads use a similar code construct.

Both code snippets shows a solution to a similar problem - wait until an action happens in another thread before continuing the current thread execution.

 

So I shouldn't use Sleep?

No, there is nothing wrong with using Thread.Sleep when needed. However the examples above shows how it can been misused.

 

  • The 1st snippet shows Sleep as a way to wait till a thread has done some work and exited.
    Using Sleep introduce an unknown/random factor to your code.
    What happens if the created thread didn't finish before the sleep - should we increase the wait time?
  • The 2nd snippet shows sleep as a way to sync two threads.
    Another thread change someArgument value an action has been performed. However CPU cycles are wasted checking the argument before each sleep.

 

There are better ways to solve those problems:

1. Use Thread.Join

2. EventWaitHandle

 

Thread.Join

We use Join when we want to wait till another thread ends.

Thread t1 = new Thread(() => Console.WriteLine("Thread 1 working"));

 

t1.Start();

// do some work

t1.Join();

// continue execution

No random results - a simple solution that always works.

EventWaitHandle

EventWaitHandle has very low CPU overhead and should can be to used to pause a thread until a signal is received.

static EventWaitHandle waitEventHandle = new AutoResetEvent(true);

public void DoWork()

{

    Console.WriteLine("Thread 1 working");

 

    // Do Some Work

 

    waitEventHandle.Set();

 

    // Do more Work

}

 

public void WaitThread()

{

    new Thread(DoWork).Start();

 

    waitEventHandle.WaitOne();

 

    //...

}

 

In this code snippet instead of using a loop and a shared variable we use AutoResetEvent so that WaitThreadthread can wait until DoWork thread signals.

 

Comment?

Wednesday, July 16, 2008

Over-specification In Tests

Szczepan Faber wrote on worrying about the unexpected. By that he means that your tests try to step outside the specific assertion boundary, and try to identify "unexpected" behavior. He describes his views on state and interaction based testing, and when (and when not) to write these kind of tests. This is a good example on how fragile your test code can get.

It's always amazing on how you can make things more complex, with very little effort.

Awhile ago, we had a logic component we wanted to write in TDD. It had a dependency on the registry, so we used Isolator to mock these dependencies. This was simple enough. And the outcome was brittle as a ... very brittle thing. The tests passed, but we had to go in and change them over and over again. That was because the method calls changed, the order of calling changed, and so on. And every time we made changes to the internals, the test code had to change too.  The tests knew too much about the internals of the code.

Newsflash: Over-specification is bad. And like many things in life, you need to learn that through trial by fire.

The problem gets worse when you're doing TDD. If you find yourself going back and forth, changing expectations and code, you have a problem. You probably need to do some refactoring first (and some thinking never hurts, too).

And by "You" I mean "We", and especially "I".

Mocking asynchronous actions with Typemock Isolator

Here is an answer to a question that keeps popping up every once in a while: how do you stub out asynchronous actions in your class under test? Assuming that you can't\won't change the code and refactor it (usual case in most legacy systems), here is a class with an async action you'd like to stub:

 public class ClassWithAsync

    {

        public void Do(int input,Action<int> resultCallback)

        {

            ThreadPool.QueueUserWorkItem(state =>

                                            {

                                                Thread.Sleep(1000*3);

                                                resultCallback(input*2);

                                            });

        }

    }

 

The ThreadPool.QueueUserWorkItem will invoke our callback asynchronously. Here are two versions of the same test that you can write. The first one is the strogly typed version, which will required the pro or enterprise versions of Typemock Isolator. The second one will work with the free community edition of Typemock.

 

   10 [Test]

   11         public void AsyncMocking_NaturalMocks()

   12         {

   13             bool wasCalled = false;

   14             int passedResult = 0;

   15 

   16             ClassWithAsync target = RecorderManager.CreateMockedObject<ClassWithAsync>();

   17 

   18             using (RecordExpectations rec = new RecordExpectations())

   19             {

   20                 target.Do(0,null);

   21                 rec.Return(new DynamicReturnValue(delegate(object[] parameters, object context)

   22                                                       {

   23                                                           Action<int> theUserCallback =

   24                                                               parameters[1] as Action<int>;

   25                                                           theUserCallback(11);

   26                                                           return null;

   27 

   28                                                       }));

   29             }

   30 

   31             target.Do(5, delegate(int result)

   32             {

   33                 passedResult = result;

   34                 wasCalled = true;

   35             });

   36             Assert.IsTrue(wasCalled);

   37             Assert.AreEqual(11, passedResult);

   38 

   39         }

The way this test works:

in line 16: we create a mocked version of the class we'd like to stub out. then we start a recording session with Isolator where all method calls are recorded. in line 20 we invoke the method for recording purposes. essentially saying "a call to target.do()" will be made later.  any parameters we pass in that line are ignored.

rec.Return tells the recorder what to return or execute when the method is actually called. in this case we are create something called a DynamicReturnValue which allows us to send in our own delegate that does whatever we want. in this case we are taking in the parameters that were sent to this method (the second one is the user's delegate).

when the recording block has ended (the end of the using block) we simply invoke the class. this is code that will usually not be in a test, but will be in the production code that we invoke. we are just simulating what the production code might do. we pass in our own delegate as the callback to the method, and in it we just set some variables that we will assert against.  (We pass in 11 to show that we control the output. the original class would have returned 10.

Here is the community edition version of this test: no record\replay support but should work just the same:

 

   13 [Test]

   14         public void AsyncMocking_ReflectiveMocks()

   15         {

   16             bool wasCalled = false;

   17             int passedResult = 0;

   18 

   19             MockObject<ClassWithAsync> mockObject = MockManager.MockObject<ClassWithAsync>();

   20             mockObject.ExpectAndReturn("Do",

                                         new DynamicReturnValue(delegate(object[] parameters, object context)

   21                                                     {

   22                                                      Action<int> theUserCallback =

   23                                                      parameters[1] as Action<int>;

   24                                                      theUserCallback(((int)parameters[0]) *2 +1);

   25                                                      return null;

   26 

   27                                                     }));

   28 

   29             ClassWithAsync mockedClass = mockObject.MockedInstance;

   30             mockedClass.Do(5, delegate(int result)

   31                                   {

   32                                       passedResult = result;

   33                                       wasCalled = true;

   34                                   });

   35             Assert.IsTrue(wasCalled);

   36             Assert.AreEqual(11,passedResult);

   37 

   38         }

 

Any questions?

Tuesday, July 15, 2008

Configuration via Typemock Interception

A while ago Udi Dahan wrote that he'd like a way to configure objects by just setting property values on an object. those "setters" will be intercepted and saved to a some config object (or container) for the future use of the application.

Udi turned to me a while ago and asked if perhaps typemock could be used to do this. an unusual scenario for a mocking framework, but a valid one for an AOP framework (which typemock is sort of)

It lost my mind after a while but today I talked with udi again, and came up with a simple solution to his problem. Here is a simple class that can be used like this:

 

        [Test]

        public void HandleCallsOn_OnlyFirstInstanceGetsIntercepted()

        {

            List<object> args = new List<object>();

            MyClass configure =

                TypeHandler.HandlePropertyCallsOn<MyClass>(

                     delegate(Type type, string propertyName, object passedValue)

                              {

                                 args.Add(passedValue);

                              });

 

            configure.ConnectionString = "a";

            configure.SomeNumber = 3;

            new MyClass().ConnectionString = "b";

            Assert.AreEqual(2,args.Count);

 

        }

Calling "HandlePropertyCallsOn" and giving a callback allows you to do whatever you want when the properties are set (the real properties are never really set). The BIG plus is that the properties do not have to virtual for this to work.

 

here is the code of the class that does this. you can use this with the free Community Edition of Typemock Isolator by just adding a reference to it in your project.

 

Just copy this class into your project to use it.

 public class TypeHandler

    {

        public static TFrom HandlePropertyCallsOn<TFrom>(Action<Type, string, object> callback)

        {

            MockObject<TFrom> mock = MockManager.MockObject<TFrom>(Constructor.NotMocked);

            mock.MockMethodCalled+=delegate(object sender, MockMethodCallEventArgs e1)

                                       {

                                           callback(typeof(TFrom), e1.CalledMethodName, e1.SentArguments[0]);

                                       };

 

 

            foreach (PropertyInfo property in typeof(TFrom).GetProperties(BindingFlags.Public|BindingFlags.Instance))

            {

                mock.ExpectSetAlways(property.Name);

            }

            return mock.Object;

        }

    }

 

you can use this class to configure calls on even interfaces without having a real class on them, or on abstract classes and such.

Monday, July 14, 2008

Why Do I Write Unit Tests?

There are many articles and blogs out there explaining the advantages of AUT. Here is my small take on the question "why do I write unit tests?"

1) I really want to keep my boss (and my wife) happy. When he's happy, he lets me be. When he is happy he doesn't feel the need to ask questions which I need to answer. And most important, when he is happy, (And I am lucky) on that yearly review I might just score that nice fat raise I'm waiting for.

So, how to make a boss happy? luckily for programmers that's real simple. We just need to finish a little bit more the we committed to, a couple of days before the deadline with zero defects. Although I'm not sure AUT will help me achieve the first two (actually I feel they do help on this, I'm just not sure), actually testing the code is probably mandatory if I ever want to achieve the last.

2) I really like doing new things all the time. However, in order to start something new, I first must finish what I'm working on now. And before I can say I'm finished I really should test it. Having a nice set of tests allow me to say: "look, here are my 20 test cases for these 2 simple methods. The code is tested. What's next?"

3) The last thing I want are incoming defects. I hate it when the QA guy (or even worse a customer) pop that horrified "you have this bug" email. Not only that this does not make my boss happy, usually those guys have the really weird notion that I should actually fix the bug. In most case this kind of prevent me from finishing what I'm doing NOW and starting a new thing. I really do need to properly test things if I ever wish to avoid this.

4) I like writing code. I'm not too keen on manual testing. I'm a programmer not a tester. Writing code is what I do for living, it would be a real shame if I didn't enjoy it. Still, I really do need to test my code properly. Did I've just managed to convince everyone that I can test my code by writing more code? cool!!! I can work with that.

5) I'm lazy. I've just finished this 4 weeks coding sprint. Oops now I need to make sure its tested. There's a real chance I'll really attempt to manually test it, once!. If my boss really push me hard (and I mean hard), I might be willing to attempt that again. You might as well shot me in the head before asking me to repeat it for the 3rd time. I am however willing to invest some effort in automating this process (after all its just writing some more code).

6) I have a real short memory. Although I can remember my childhood phone number and various other useless pieces of information, in a couple of weeks most likely that the guy sitting next to me will remember more on what this code I'm writing now does. I'll will be really amazed (shocked actually) if I will remember how to manually test it all over again. Writing the test down is the only sure way I know to remember how to test things. (With some luck, reading the tests will also jump me started on what I was thinking when at that time\).

But seriously, after doing TDD for some time now it really helped me achieve all these things.

Done right AUT will:

1) Reduce the defect rate. Which both tend to keep my boss happy and reduce the times I need to go back to fix them.

2) Help me gain enough confidence in my work. Confidence which allows me to move onwards without self doubts and fear.

3) Turn the tedious task of manual testing, into something I can repeat over and over again. (It's actually fun from time to time to fix a defect and be amazed that ALL the other tests are showing green.)

4) Document my work in a manner which helps me (or anyone else) understand what needs to be done when coming back later on, and has a good chance to stay updated as time go by.

There are many other reasons as why do writing automated tests is really good. But at the end of the day these are the reason why I do it. (oh and the fact that everyone here would make fun of me if I didn't).

Racing Philosophers

This post describes a known deadlock problem and how Typemock Racer can be used to discover deadlocks in .NET code.

You can read more about Typemock Racer at ISerializable Blog.

 

Overview

The well known computer science problem called Dining philosophers was invented by E. W. Dijkstra:image

A number of philosophers (usually five but it could work with any number larger than two) sitting around a table thinking about philosophical problems.  Each philosopher has a bowl of rice and two chopsticks he can use to eat it.

Every now and then a philosopher gets hungry and grabs his two chopsticks so he can eats.

 

So far so good - However to complicate things the philosophers share their chopsticks.

Each philosopher's right chopstick is shared with his neighbor on the right and his left chopstick is shared with his neighbor on the left.

 

The problem

what happens if Plato would pick his right chopstick but when he tries to grab his left chopstick it is already taken by his colleague‏‏‏‏?

Obviously being Plato he is patient enough to wait till his fellow thinker finish his snack and put his chopsticks down. however to insure that he does get to eat in the near future Plato keeps the chopstick he managed to get till he can grab the other chopstick.

This behavior can cause a deadlock if each philosopher takes the chopstick to his right at the same time.

 

The program

As we can see from the story each philosopher does the following actions:

  1. Think for a while
  2. Take the chopstick to your right
  3. Take the chopstick to your left
  4. Eat
  5. Put down the chopstick in your left hand
  6. Put down the chopstick in your right hand

 

As you can already see we can implement this behavior using locks - each chopstick is an object that the philosopher tries to lock. 

My implementation uses three classes:

1. Philosopher - to contain the bulk of our problem logic

2. Chopstick - I could use simple object instead but I like to properly define my classes

3. Table - to contain the overall problem domain

 

Philosopher class has left and right chopsticks and two functions: Think and TryToEat.

As you can see from the code below TryToEat use lock to acquire the chopsticks and then eat and exit.

 

public class Philosopher
{
private ChopStick rightChopstick, leftChopstick;
private int timeToThink;
private string name;

public Philosopher(string name, ChopStick rightChopstick, ChopStick leftChopstick, int timeToThink)
{
this.name = name;
this.rightChopstick = rightChopstick;
this.leftChopstick = leftChopstick;
this.timeToThink = timeToThink;
IsAlive = true;
}

public string Name { get { return name; } }
public bool IsAlive { get; set; }

public void Run()
{
while (IsAlive)
{
Think();
TryToEat();
}
}

public void Think()
{
Console.WriteLine("{0} is thinking", name);
Thread.Sleep(timeToThink);
Console.WriteLine("{0} done thinking", name);
}

public void TryToEat()
{
lock (rightChopstick)
{
Console.WriteLine("{0} grabbed right Chopstick", name);
lock (leftChopstick)
{
Console.WriteLine("{0} grabbed Left chopstick", name);
Console.WriteLine("{0} is eating", name);
}
}

Console.WriteLine("{0} has finished eating", name);
}
}


Remark:



in the real program I would have used Thread.Sleep to simulate the time it takes the philosopher to eat but for the example purpose I can do without it.



 



Typemock Racer



As we can tell the deadlock would happen in TryToEat function and so we can write the following test to check it:



[TestFixture]
public class DiningPhiloRacer
{
[Test]
public void DiningPhilosefers_Run_FindDeadlock()
{
var c1 = new ChopStick();
var c2 = new ChopStick();
var c3 = new ChopStick();

ThreadTest
.AddThreadAction(() => new Philosopher("Plato", c1, c2, 0).TryToEat())
.AddThreadAction(() => new Philosopher("Konfucius", c2, c3, 0).TryToEat())
.AddThreadAction(() => new Philosopher("Socrates", c3, c1, 0).TryToEat())
.Start();
}
}


 



Running the test is as simple as clicking a mouse button - and presto deadlock found.



diningPhilosophersDeadlock



Under the deadlock message we can see the scenario that caused the deadlock and with stack trace (blue rectangle) and if that's not enough the user is given an attribute (yellow rectangle) he can use in his\her test to quickly reproduce the scenario that caused the deadlock.



 



That's it for now



 



Stay tuned for other uses and tips from the Racer team

ALT.NET Israel registration is open

The registration for ALT.NET Israel is now open. You will need an OpenID (I use myopenid.com) to register. We are limited to 50 seats for the first event. First come first served. Worst case scenario you go into the waiting list.

Please only register if you are serious about attending.

The event takes place in two parts: Thursday eve. from 18:.30 to 20.30 and then the full day on friday (9-17.00). more details on the site.

Sunday, July 13, 2008

ALT.NET Israel - August 7th-8th 2008

I'm really happy to announce that we are going to have a small (30-70 people) ALT.NET Open Space event in Israel. The full details can be seen on Ken Egozi's blog. Ken is the one who drove Oren and myself into finally getting off our big butts and do this, but he's the one who find the nice location (SQLink offices) and we have Typemock to sponsor food and drinks for the conference.

Registration is not open yet. once the site is ready I will announce it. it is free on a first come first served basis and once we have all the spots filled up you will be put in a waiting list. It will take place on August 7-8 (3 weeks from now!) in Ramat Gan.

In the tradition of open spaces, the first half day (we meet in the evening of thursday) will be devoted to coming up with an agenda for the next day. the next (full day) will be totally run by the attendees. Should be lots of fun!

10 good unit testing tips

Those of us taking the first steps in the world of unit testing (and the rest who could use a reminder) can find some good tips here. I could relate to most (especially point #1: You’ll probably suck at testing).

Wednesday, July 9, 2008

Musings about Refactoring

For the last couple of weeks I've been paired with Lior on a large refactoring task that was long overdue. We did not have any specific bug to fix, but rather wanted to simplify some of the dustier corners of our codebase. This really helped me realize the importance of refactoring, and specifically of doing it frequently.


The first thing I noticed was that both of us struggled when reading the code; it was not badly written - there were messy parts and elegant parts like anywhere else - it was just alien to us. We did not know what the author meant when writing the code, the naming convention was confusing to us and the reasons behind some of the trickier stuff were a mystery to us.


Now, after major renaming, commenting out, deleting, simplifying and extracting, we believe the code is simpler and more readable. However, I believe that if we leave it at that in a couple of years another pair may be in the exact same situation - our code may be mystifying to them, no matter how self descriptive we tried to make it. By refactoring frequently this can be avoided, or at least minimized.


Refactoring is easy to neglect; in the TDD cycle we never forget to write tests, implement code and test it, but it's easy to leave it at that once all tests passed. I intend to put emphasize on doing another refactor + test run on any code I product, in order to make sure I did my best to keep it simple. Also, when fixing something I fully intend to look beyond the immediate fix (which may be something small like adding an 'if' condition), and go over the entire method/class I modified. You may write code that flows like poetry, but after patching it a couple of times the rhymes will be off and the punch line is gone. This may not seem important when trying to get as many features as possible out the door, but missing it may have severe effect on the quality of the code base, the time it takes new people to learn it and how testable it is.

Monday, July 7, 2008

Unmanaged Code Unit Testing

Living in the managed world is wonderful. But sometimes we carry a small legacy code in C++. Ok, it happens a lot. And a while back, I worked on a large application and thought – how do I introduce unit-tests there?

There’s a video posted on MSDN. It shows how to use VS Team System to test C++ COM objects. Basic stuff.

Basic indeed. Watching this video reminded me of that situation. Then we considered using a C++ framework, which didn’t work out. Code was too complicated to test. And we had VS 2005 Team System under our noses.

We know that in order to achieve better code quality, we need to make an effort. But don’t drop tools from the list, just because they don’t seem to fit at first. Today, VS 2008 Professional already has unit testing in it – use it. It got code coverage – use it. It doesn’t have all the C# and VB.Net bells and whistles – use it anyway. Any safety net is better than no net at all.

And then Integrate it into you build system. And add more tests as you continue. No more excuses.

Saturday, July 5, 2008

Dynamic Return Value and Mock Abuse

Oren (Ayende) wrote about mock abuse. In his example an entire behavior is substituted using the mocking framework. It's a really good example for what not to do.

How is it done? Note the Do segment of the call:

stubbedIncomingMessageRepository
.Stub(x => x.GetEarliestMessage())
.Return(null)
.Do(invocation =>
{
lock (msgQueue)
{
invocation.ReturnValue = msgQueue.Count == 0 ? null : msgQueue.Dequeue();
}
})
.Repeat.Any();
It replaces the original method with another implementation, which is invoked when the original method is called.

The equivalent in Typemock Isolator is called "Dynamic return values". It allows you to perform any implementation instead of an original one, and return a value based on that implementation.

It's very powerful. You can do magic with it. But don't abuse it. Keep your tests simple and readable.

Tuesday, July 1, 2008

Isolator 4.3 Released!

It’s time for another release! It’s version 4.3 of Typemock Isolator. Download it from here.

What’s new?

  • The first thing I want to mention here is support for Ivonna. It is already possible to purchase an Ivonna license through our site here. Once you receive a license, you can simply enter it through the Typemock Configuration GUI (Under the License tab). Just select Ivonna from the combo box. For those of you who develop ASP.Net applications and who still haven’t tried Ivonna – I suggest you go try it NOW. It’s a great tool, built on top of Isolator’s platform, to simplify writing tests for ASP.Net.
  • And on you’ll notice the Typemock.Integration.Packs namespace APIs we added to support license management through Isolator, the way Ivonna does. If you want to build your own add-on pack, let us know!
  • We warned you when we released 4.2 that this would be the last version of Isolator to support .Net 1.1. We weren’t lying. Version 4.3 does not support it. It is our way of saying: Get current, dude.
  • And for those fortunate people with 64 bit machines, listen to this: A single installer! Yes, finally. Make sure that when you upgrade, you uninstall BOTH previous 32 and 64 installers prior to installing 4.3. (For a very few of you, fortunate as you are, you may need to re-enter your license after the installation. You’ll see that in the Configuration window both Company and License fields will be empty).
  • A new API we’ve added: RecorderManager.GetMockOf(instanceRef) and its brother MockManager.GetMockOf(instanceRef). This allows you retrieve the mock controller object based on a reference to the instance. You can read more about it here.

There’s a whole list of fixes I’ll get them in a minute. But first the issue of LINQ.

LINQ. We thought we had it right in 4.2.4. We didn’t. Different support cases of LINQ usages, especially DLINQ, were thrown in our faces. Each with its own expression tree. So now DLINQ support is much better (we do know of one issue that still requires a fix) but this time we’re not saying it’s perfect. We understand it will take awhile until we’ve covered every case. Prove us right.

Here’s the list of bug fixes, since 4.2.4:

  • Fixes to DLINQ support. LINQ Queries with data tables now work better, for example with GroupBy.
  • Static constructors in Natural Mocks are now invoked correctly.
  • A bug that caused an exception to be thrown when mocking interfaces ("Method XX in type IMyInterface has no matching overload that returns TypeMock.Mock+a) was fixed.
  • A bug that caused an exception to be thrown when the mocked object was overriding Equals was fixed.
  • A bug that caused failure in mocking explicit interface with the same name was fixed.
  • A bug ocurring im multithreading scenarios in VerifyWithWait was fixed.
  • A bug that causes NullReferenceException to be thrown when using Auto Deploy was fixed.

    So go download it. Now. What, you’re still reading this? I said go.

  • Sunday, June 29, 2008

    Getting mock object from an instance

    Hi All,

    In our upcoming 4.3 version we're adding the possibility to get a mock object directly from the instance it has been assigned for. Previously this has been possible through use of MockManager.GetMocks<>() and iterating through the results, or by retrieving the latest mock in a recording block using RecorderManager.GetLastRecorderMock().

    So what is this good for? If you're mocking multiple objects in a Natural Mocks recording block and want to quickly identify the mock object mapped to one of them, you can use RecorderManager.GetMockOf() to do the job. The mock object you retrieved can then be used to mock private methods etc.

    Lets see a quick example: here we're using GetMockOf() to get the mock object mapped to an instance and use that mock object to mock a private method call, affecting test results:

    [TestMethod]
    public void CountNotZero_InventoryNotEmpty()
    {
    using (RecordExpectations rec = RecorderManager.StartRecording())
    {
    Warehouse mockedInstance = new Warehouse();

    // we want to mock CountInventory(). In order to do this we retrieve the mock object mapped to the mocked instance
    Mock<warehouse> mock = RecorderManager.GetMockOf<Warehouse>(mockedInstance);
    mock.ExpectAndReturn("CountInventory", 10);
    }

    Warehouse target = new Warehouse();

    // the mocked CountInventory() will be called so InventoryEmpty should be false
    Assert.IsFalse(target.InventoryEmpty);
    }

    This new API came from a user request, and is the result of ongoing conversations we are having with our users community in the forums and through our support mailbox. So - what API would make Typemock work better for you?