24/02/2009

Using mock4as for testing

We have reciently introduced mock4as in our project, I found it very easy to use and very helpfull when mocking for tests.

I don´t pretend to write a full especification on how to use it, you can find that in deep detail on their site, so I´m just going to post a tiny example so you can have a quick idea of how it works, lets test a serer call on a delegate:

First of all we need to create a Mock delegate for out tests (a nice approach to do this is just to implement the same interface both on your delegate and on your mock delegate). This mock delegate neds to have a PUBLIC variable of the type "Mock" (from the mock4as framework:

MyMockDelegate.as:
public var mock : Mock = new Mock();
So from our Test class we are going to tell the mock variable which call we spect Flex to do, then we will trigger the action that is supposed to do that call and add the assertion to see if the call was eventually done or not:

MyTest.as
public function testSomething () : void
{
myMockDelegate.mock.expects("getSomething");
somePM.trigger();
assertTrue( myMockDelegate.mock.errorMessage(), myMockDelegate.mock.success() );
}
And now, the only bit left is to register the call on the mock delegte:

MyMockDelegate.as
override public function getSomething( resultHandler : Function ) : void
{
mock.record( "getSomething" );
}
And thats it! So, summarizing, the execution of the test would be as follows:

1 - We tell the test what we spect to be called
2 - We call the trigger function, this will cause the app to call the mockDelegate "getSomething()" function, which will register the call into the "mock" variable.
3 - The assertions will verify that the call we where expecting was done

Piece of cake, isn´t it?

I hope it helps ;)

No comments:

Post a comment