Friday, November 09, 2007

Test callback delegate with Rhino.Mocks

Here is the case to test callback delegate by using Rhino.Mocks.

The following service class has a method with a delegate callback as parameter to get a list of products:

// somethere delegate is defined, Product is an another class
public delegate void RetrieveProductListCallback(
bool success, List<product> products);

// service class
public class ProductService
// ...
List<product> RetrieveProducts(
RetrieveProductCallbackHander callback)
{ //...

// Define a method which is used as delegate handler
private void ProductListHandler(bool success,
List<Product> products)
{ // ...

RetrieveProductListCallback callback = ProductListHandler;


What I want to test this service's callback event. There were no direct information about this issue. I spent several hours googling information on web and tested many different ways. Finally I found a way to test the callback. Here is the summary of the tricks: using Last.Callback and Predicate to do the test. Here are some codes for the test:

public void ShouldGetAllProudctsFromService()
List<Product> products = new List<Product>();
// add some products to the list
bool success = true;
// define a none-null callback
RetrieveProductListCallback callback = delegate {};

using (Mocks.Record())
// expect to call method with callback
// Here is the trick to set up callback
// to be called
RetrieveProductListCallback callbackhander)
if (callbackhander != null)
callbackhander(success, products);
return true;

// ...

using (Mocks.Playback())
// ... assert