Mocking Events [With RhinoMocks]

3 04 2008

Suppose we have an Inerface called IFooDatabase . Think this Interface as our gateway which will provide us with basic database operations.

Now, how does Mocking come here? – My friend is still working on this database layer but he has given me already the Interface with which he is implementing the Database Class, so that I can make use of that and mock, as if that database layer exists and test my program against it.

What mocking framework I am using? – RhinoMocks

My friend told me that he is going to add events for each database operation, like InsertEvent, UpdateEvent, DeleteEvent so that they may be raised for each insertion, updation and deletion operations respectively.

For this post, to make it simple, let me take just the InsertEvent. Here is the class diagram,

And here is my Class which is going to make use of this Interface

I was pretty happy that my friend provided me an Interface to mock all the database activities, but I was really stuck on how do I test all those Events are raised!

Well, been using one of the best Mocking Frameworks around, RhinoMocks did provided a way to mock Events πŸ˜‰

So, here is my test case,

[Test]

public void TestInsertEventRaised()

{

MockRepository fooDatabaseMock = new
MockRepository();

IFooDatabase

Β Β  fooDatabase = fooDatabaseMock.DynamicMock<IFooDatabase>();

fooDatabase.FooDatabaseInsertEvent += null;

LastCall.IgnoreArguments();

IEventRaiser
fooEventRaiser = LastCall.GetEventRaiser();

fooDatabaseMock.ReplayAll();

Foo myFoo = new
Foo(fooDatabase);

fooEventRaiser.Raise(this, EventArgs.Empty);

Assert.IsTrue(myFoo.InsertEventRaised);

}

RhinoMocks provides an interface called IEventRaiser which you can use to raise events!

Here is what we are doing,

  • I am assigning null to the EventHandler and telling RhinoMocks that please do ignore the arguments in my last call. This helps us because we may associate our event to any Event Handler with different event arguments
  • We initialize IEventRaiser by getting the last event, which in our case is FooDatabaseInsertEvent
  • We pass on the Database object which is mocked to my Foo class to use
  • And finally we raise that last event
  • And do a simple Boolean check to see actually we did raise the event

Wasn’t that easy πŸ˜‰

You may complain that I have used the generalized EventArgs and completed this post. What about custom EventArgs?

No worries, that also takes the same route πŸ˜‰

[Test]

public void TestUpdateEventRaised()

{

MockRepository fooDatabaseMock = new
MockRepository();

IFooDatabase

Β  fooDatabase = fooDatabaseMock.DynamicMock<IFooDatabase>();

fooDatabase.FooDatabaseUpdateEvent += null;

LastCall.IgnoreArguments();

IEventRaiser fooEventRaiser = LastCall.GetEventRaiser();

fooDatabaseMock.ReplayAll();

Foo myFoo = new
Foo(fooDatabase);

fooEventRaiser.Raise(this, new
FooDatabaseEventArgs(“datbase”,true));

Assert.IsTrue(myFoo.UpdateEventRaised);

}

The FooDatabaseEventArgs is our custom EventArgs.

I would recommend anyone reading this post to try out the sample posted below if you really want to understand what is happening πŸ˜‰

You can download the sample here





Revisiting Mock Objects

5 02 2008

My last post on Mock Objects explained briefly about what is Mocking and gave you an example. But that example is not explained and thought let me explain and how Mocking plays its part here.

So, revisiting that example,

[TestFixture]
public class AdminTests
{
    private MockRepository mocks;
    private EduAdmin eduAdmin;
    private Bl.IBLAdmin mockAdmin;
    private delegate bool ValidRegisterDelegate(Db.Admin entity);

    [SetUp]
    public void Setup()
    {
         mocks= new MockRepository();

         mockAdmin = mocks.DynamicMock<Bl.IBLAdmin>();
    }

    [Test]
    public void Check_Method_Register()
    {
        AdminEntity inputEntity = new AdminEntity();
        inputEntity.AdminId = β€œadmin”;
        inputEntity.AdminPassword = β€œadmin”;

        Db.Admin dbAdmin=new Educator.DataAccess.Admin
        {
            AdminId = β€œadmin”,
            AdminPwd = β€œadmin”
        };

        With.Mocks(mocks).Expecting(() =>
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(delegate { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) => { return entity.AdminId == β€œadmin” && entity.AdminPwd == β€œadmin”; }));

        }).Verify(delegate
       {
           eduAdmin = new EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });
    }
}

To explain the above example, consider this diagram

mock-objects-1.png

(Please consider the line separation, I will come to it later, Ignore the Tests)

So, as the diagram explains, we have,

1) EduAdmin which is our Service Layer (SL)

2) IBLAdmin which is our Business Layer (BL) Interface, and,

3) Database Layer (DL)

The BL interacts with DL to perform database operations and SL sends requests to BL in regard to what needs to be done.

So, what does the above example test function do? Here it is,

flow.png

Revisiting again the definition of Unit Testing,

In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application.

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy.

So, testing this RegisterAdmin function involves the use of BL as well DL (via the BL). And also from the first diagram, we do show that each layer is tested against their own tests. So, using Mock Objects, now we come down to,

mock-objects.png

Since we have mocked our BL, we can now write expectations on how it has to behave and what results it has to give for our Service Layer to work properly πŸ™‚

To dig deep, we may have something like this,

bl-sl.png

Admin is a class that implements our Interface IBLAdmin and AdminEntity is business type and DB.Admin is a database type.With Mocking, we don’t care about the Class but the Interface. EduAdmin is our Service Layer class and it has a function RegisterAdmin

So, to RegisterAdmin function to work properly, we have to see that the BL’s Translate and Insert functions return proper results and those are nothing but setting expectations on our mock object which is IBLAdmin 8) . If you think slowly where we are, you will probably get what is Mocking πŸ˜‰

Here is that part which sets expectations and tells what should be returned respectively

        With.Mocks(mocks).Expecting(() =>
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(delegate { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) => { return entity.AdminId == β€œadmin” && entity.AdminPwd == β€œadmin”; }));

        }).Verify(delegate
       {
           eduAdmin = new EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });

What does that ValidRegisterDelegate do? It checks whether the input parameters that is being used to invoke Insert function is of expected type and has expected values. Its more of a RhinoMocks feature, so once you start using it, you will get used to it πŸ˜€ . And RhinoMocks follows the Record and ReplayAll method where we set expectations means that we record something and once we say to verify, it replays all the set expectations when invoked.

The expectations we set are very simple. When the Translate function is called with an input parameter of type AdminEntity, return an object of type Db.Admin . Similarly for Insert function, except that we don’t return anything.

In the Verify stage, we can see that we create a new instance of our SL by passing the BL Interface object. What are we doing here? Welcome to the world of Dependency Injection πŸ˜€ . We explicitly tell that – “Hey, here is my BL object which you have to use and please use this“. We inject dependency here! So, now the BL object is already in the MockRepository and when we tell our SL to use this object, it means that its going to use the MockRepository object with expectations set on it 8)

I think now things are getting clear and you should be able to understand this diagram way better than earlier πŸ™‚ (which is also shown above)

mock-objects.png

Coming back to Dependency Injection – You may be wondering that so if my client uses this SL, will he always have to explicitly tell that this is my BL and use it? – NO. The way we overcome is using multiple constructors πŸ™‚

public class EduAdmin
{
     private IBLAdmin blAdmin;

     public EduAdmin(IBLAdmin mockAdmin)
     { blAdmin=mockAdmin;}

      public EduAdmin() : this(new Admin())
     { }
}

I think thats self explanatory on what we do πŸ˜‰

Hope this explained how we Mock 8)

If you have any doubts, please do leave your comments and I will try to answer them πŸ™‚





Mock Objects

25 01 2008

tdd.png

So, you have started reading or doing more on Test Driven Development? Then am sure you would have now heard about Mocking or Mock Objects πŸ˜€

Before getting started and seeing what is this Mock Object, let me quote the definition of Unit Test from Wikipedia

In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application.

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy.

So, Unit Testing covers testing each individual part in your program. In other words, when we say we are unit testing a Component A, we actually test the functions, properties etc., inside that component.

Below is a pictorial representation of what we do,

unit-test.png

For Component A , we write several unit test cases and test it. Since this component does not depend on anything else, it is fairly easy to test all the parts of the component and hence it satisfies the definition of Unit Testing.

Now we bring in another Component B, which depends on Component A and thus now we have something like this,

unit-test-2.png

How do we test Component B now?

Let me write down the scenario of where we are now,

1) We have Component A which is been tested

2) We have Component B which uses/depends on some of the functions of Component A

3) We have to test Component B such a way that its isolated from Component A, yet still use Component A

4) If we test along with Component A with Component B, its not Unit Test, rather its, Integration Testing!

What do we do now? Mock Component A 8)

Yes, here comes the use of Mock Objects. From Wikipedia,

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

So, its kinda Fake Object, but a Mock Object has some expectations and results being set on it.

Now, to make use of Mock Objects, we change the Component A to implement an interface Interface A and Component B an interface Interface B .Using Interfaces helps us to have just the functions and properties of the Component being written which is what Mock needs πŸ˜‰

Here we are now,

unit-test-3.png

TDD has hence allowed to make changes to your design now and you would have changed tests accordingly.

Introducing Mock Objects, we now have,

unit-test-mocking.png

So, we interact with Component A using our Mock Repository which holds the Mock Object – Interface A

We can now set expectations on Mock Objects, meaning that, you can say that – When a function named FunctionA is called, return the string “Hello World”

It may confuse you initially, but am sure you will get the whole picture once you start mocking yourself πŸ˜‰

Here is a sample test case along with Mocking (Using NUnit and Rhino Mocks),

[TestFixture]
public class AdminTests
{
    private MockRepository mocks;
    private EduAdmin eduAdmin;
    private Bl.IBLAdmin mockAdmin;
    private delegate bool ValidRegisterDelegate(Db.Admin entity);

    [SetUp]
    public void Setup()
    {
         mocks= new MockRepository();

         mockAdmin = mocks.DynamicMock<Bl.IBLAdmin>();
    }

    [Test]
    public void Check_Method_Register()
    {
        AdminEntity inputEntity = new AdminEntity();
        inputEntity.AdminId = "admin";
        inputEntity.AdminPassword = "admin";

        Db.Admin dbAdmin=new Educator.DataAccess.Admin
        {
            AdminId = "admin",
            AdminPwd = "admin"
        };

        With.Mocks(mocks).Expecting(() =>
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(delegate { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) => { return entity.AdminId == "admin" && entity.AdminPwd == "admin"; }));

        }).Verify(delegate
       {
           eduAdmin = new EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });
    }
}

More resources on Mock Objects,

1) All about Mock Objects

2) Mock aren’t Stubs

3) Rhino Mocks