Monday, October 20, 2008

Using NMock2

In unit testing, sometimes it is needed to isolate the dependencies in order to test a specific part of the application.

One way to do that is using mock objects. They simulate the behavior of real objects and is not needed the entire application for the test.

For example, in a Restaurant, the Waiter's job depends on the Cook's job . So, when you test the Waiter's job, you will test the job of the two employees.


If you want to test only de Waiter's job, you need to create a mock object in order to simulate the other employee's jobs.


NMock2 is one option to create mock objects. It can be downloaded from http://www.nmock.org/. As follows you will find the code to create the mock of the Cook using NMock2:




// Create the order and dishes for the test
Order order = CreateOrder();
List<Dish> dishes = CreateDishes(order);


// Create the mock of the Cook
Mockery mockery = new Mockery();
ICook cook = mockery.NewMock<ICook>();
Expect.Once.On(cook).Method("GetDishes").With(order)
.Will(Return.Value(dishes));


// Asign the mock object as Cook of the restaurant
Restaurant.Cook = cook;


// Send the order to the Waiter
Waiter waiter = new Waiter();
waiter.ProcessOrder(order);



The previous code builds a mock that expects one execution of the GetDishes method with the order as a parameter, and it must return the list of dishes specified.

So, when this test is executed, the Waiter uses the mock of the Cook, which returns the dishes that we have created.


For more details about creating mocks, you can watch the video (in Spanish language) with the entire explanation and download the presentation and code (in Spanish language).



Thanks to Miguel and Rodolfo for helping me with the video.

Monday, October 13, 2008

Using the EventLog

Many applications report errors with the EventLog because it provides a simple and centralized way to log. If you use the EventLog you won't have to worry about the size or location of the log.


Some Tips:

Use the EventLog not only for errors. Warnings and other messages are useful in order to understand the application behavior in production environments.

 

If the Source hasn't been created yet, it will be created with the first entry. That operation needs special permissions so, if the application doesn't run with administrator permissions, you must create the Source previously (see EventLogInstaller class).

 

Use some mechanism in order to filter the type of message you want to log. If not, you will have the EventLog full of messages that you don't need. (see TraceSwitch class).

 

Don't forget to use the Event ID. There are many management applications (i.e. MOM/SCOM) that use this information to take different actions.

 

You should document every entry. It will be useful when you are not there to give support.

 

For more details see the EventLog class documentation.