Tuesday, January 13, 2009

Mocking Around

While I have been playing with NMock library I found out that NUnit includes mock library as well. Never came across that before. I am ashamed, I admit.
Nonetheless, NMock has better syntax and seems more intuitive to use. The advantage of NUnit mock library is that it is a part of NUnit package. That advantage goes away, though, when unit testing libraries from .Net Framework are used for unit testing.

NUnit's mock library has a weird case when properties are accessed as the syntax for accessing a property has to include "get_" or "set_" before the property name. Also, the accessing of the property itself is a bit counterintuitive. NMock, on the contrary, offers ease of use as the mock object implements the interface and can be used in tests in a very simple and straightforward manner. It is a matter of preference. I prefer it simple.

Another thing I found out about mock objects is that they have to mock Interfaces, not Classes. While this may be obvious to some, I did not realize before what is the issue with creating all the interfaces. Now I have to look at that aspect of TDD. Some redefinition will occour on the way I develop software and hopefully the results will be even easier maintenance of the code I write as well as reusability.
One issue I ran into is that interfaces have to be public. While this may be obvious to some, it is new to me. And it is an issue to have in mind.

Now, having a mock framework in place, the stage is set for some real unit testing. The tests I did before were not pure unit tests because all the units (classes) had their dependencies on other units, or data, or some other external unit. Off to do some real TDD... :)


Here is a sample unit test:

public void test_nmock()
Mockery mock = new Mockery();
ISetting s = null;

s = mock.NewMock();
catch (Exception ex)


Assert.AreEqual("35", s.SettingValue);

No comments: