Mehfuz's WebLog

Live crazy, think different!

Sponsors

News

Passionate about cutting edge technologies and facinated by the modern web and phone revolution.Currently working at Telerik Corporation, the leading .net component vendor.
Follow me


Articles


Projects

April 2010 - Posts

Playing with aspx page cycle using JustMock

In this post , I will cover a test code that will mock the various elements needed to complete a HTTP page request and  assert the expected page cycle steps. To begin, i have a simple enumeration that has my predefined page steps:

  1. public enum PageStep
  2. {
  3.     PreInit,
  4.     Load,
  5.     PreRender,
  6.     UnLoad
  7. }

Once doing so, i  first created the page object [not mocking].

  1. Page page = new Page();

Here, our target is to fire up the page process through ProcessRequest call, now if we take a look inside the method with reflector.net,  the call trace will go like : ProcessRequest –> ProcessRequestWithNoAssert –> SetInstrinsics –> Finallly ProcessRequest. Inside SetInstrinsics ,  it requires calls from HttpRequest, HttpResponse and HttpBrowserCababilities. Using this clue at hand, we can easily know the classes / calls  we need to mock in order to get through the expected call.

Accordingly, for  HttpBrowserCapabilities our required mock code will look like:

  1. var browser = Mock.Create<HttpBrowserCapabilities>();
  2. // Arrange
  3. Mock.Arrange(() => browser.PreferredRenderingMime).Returns("text/html");
  4. Mock.Arrange(() => browser.PreferredResponseEncoding).Returns("UTF-8");
  5. Mock.Arrange(() => browser.PreferredRequestEncoding).Returns("UTF-8");

Now, HttpBrowserCapabilities is get through [Instance]HttpRequest.Browser. Therefore, we create the HttpRequest mock:

  1. var request = Mock.Create<HttpRequest>();

Then , add the required get call :

  1. Mock.Arrange(() => request.Browser).Returns(browser);

As, [instance]Browser.PerferrredResponseEncoding and [instance]Browser.PreferredResponseEncoding  are also set to the request object and to make that they are set properly, we can add the following lines as well [not required though].

  1. bool requestContentEncodingSet = false;
  2. Mock.ArrangeSet(() => request.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() =>  requestContentEncodingSet = true);

Similarly, for response we can write:

  1.  var response = Mock.Create<HttpResponse>();
  2.  
  3.  bool responseContentEncodingSet = false;
  4.  Mock.ArrangeSet(() => response.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() => responseContentEncodingSet = true);

Finally , I created a mock of HttpContext and set the Request and Response properties that will returns the mocked version.

  1. var context = Mock.Create<HttpContext>();
  2.  
  3. Mock.Arrange(() => context.Request).Returns(request);
  4. Mock.Arrange(() => context.Response).Returns(response);

As, Page internally calls RenderControl method , we just need to replace that with our one and optionally we can check if  invoked properly:

  1. bool rendered = false;
  2. Mock.Arrange(() => page.RenderControl(Arg.Any<HtmlTextWriter>())).DoInstead(() => rendered = true);

That’s  it, the rest of the code is simple,  where  i asserted the page cycle with the PageSteps that i defined earlier:

  1. var pageSteps = new Queue<PageStep>();
  2.  
  3. page.PreInit +=delegate { pageSteps.Enqueue(PageStep.PreInit); };
  4. page.Load += delegate { pageSteps.Enqueue(PageStep.Load); };
  5. page.PreRender += delegate { pageSteps.Enqueue(PageStep.PreRender);};
  6. page.Unload +=delegate { pageSteps.Enqueue(PageStep.UnLoad);};
  7.  
  8. page.ProcessRequest(context);
  9.  
  10. Assert.True(requestContentEncodingSet);
  11. Assert.True(responseContentEncodingSet);
  12. Assert.True(rendered);
  13.  
  14. Assert.Equal(pageSteps.Dequeue(), PageStep.PreInit);
  15. Assert.Equal(pageSteps.Dequeue(), PageStep.Load);
  16. Assert.Equal(pageSteps.Dequeue(), PageStep.PreRender);
  17. Assert.Equal(pageSteps.Dequeue(), PageStep.UnLoad);
  18.  
  19. Mock.Assert(request);
  20. Mock.Assert(response);

You can get the test class shown in this post here to give a try by yourself with of course JustMock :-).

Enjoy!!

Posted: Apr 29 2010, 11:23 PM by mehfuzh | with 2 comment(s) |
Filed under: , , ,
Working with multiple interfaces on a single mock.

Today , I will cover a very simple topic, which can be useful in cases we want to mock different interfaces on our expected mock object.  Our target interface is simple and it looks like:

  1.  
  2. public interface IFoo : IDisposable
  3. {
  4.     void Do();
  5. }

Our target interface has an IDisposable implemented. Now, generally if we implement it in a class , we have to implement the whole of it [which is quite logical] and that should not wait for any extra calls or constructs. Considering that, when we are creating our target mock it should also implement all the dependent interfaces for us as well.  

Therefore,  as we are creating our mock using Mock.Create<IFoo> like that follows, it also implements the dependencies for us :

  1. var foo = Mock.Create<IFoo>();

Then,  as we are interested only in IDisposable calls, we just need to do the following:

  1. var iDisposable = foo as IDisposable;

Finally, we proceed with our existing mock code. Considering the current context, I will check if the dispose method has invoked our mock code successfully.

 

  1. bool called = false;
  2.  
  3. Mock.Arrange(() => iDisposable.Dispose()).DoInstead(() => called = true);
  4.  
  5.  
  6. iDisposable.Dispose();
  7.  
  8. Assert.True(called);

 

Further, we assert our expectation as follows:

  1. Mock.Assert(() => iDisposable.Dispose(), Occurs.Once());

 

Hopefully that will help a bit and stay tuned.

Enjoy!!

Posted: Apr 26 2010, 10:35 PM by mehfuzh | with 3 comment(s) |
Filed under: , , ,
Asserting with JustMock

In this post, i will be digging in a bit deep on Mock.Assert. This is the continuation from previous post and covers up the ways you can use assert for your mock expectations. I have used another traditional sample of Talisker that has a warehouse [Collaborator] and an order class [SUT] that will call upon the warehouse to see the stock and fill it up with items.

Our sample, interface of warehouse and order looks similar to :

  1. public interface IWarehouse
  2. {
  3.     bool HasInventory(string productName, int quantity);
  4.     void Remove(string productName, int quantity);
  5. }
  6.  
  7. public class Order
  8. {
  9.     public string ProductName { get; private set; }
  10.     public int Quantity { get; private set; }
  11.     public bool IsFilled { get; private set; }
  12.  
  13.     public Order(string productName, int quantity)
  14.     {
  15.         this.ProductName = productName;
  16.         this.Quantity = quantity;
  17.     }
  18.  
  19.     public void Fill(IWarehouse warehouse)
  20.     {
  21.         if (warehouse.HasInventory(ProductName, Quantity))
  22.         {
  23.             warehouse.Remove(ProductName, Quantity);
  24.             IsFilled = true;
  25.         }
  26.     }
  27.  
  28. }

 

Our first example deals with mock object assertion [my take] / assert all scenario. This will only act on the setups that has this “MustBeCalled” flag associated. To be more specific , lets first consider the following test code:

  1.    var order = new Order(TALISKER, 0);
  2.    var wareHouse = Mock.Create<IWarehouse>();
  3.  
  4.    Mock.Arrange(() => wareHouse.HasInventory(Arg.Any<string>(), 0)).Returns(true).MustBeCalled();
  5.    Mock.Arrange(() => wareHouse.Remove(Arg.Any<string>(), 0)).Throws(new InvalidOperationException()).MustBeCalled();
  6.    Mock.Arrange(() => wareHouse.Remove(Arg.Any<string>(), 100)).Throws(new InvalidOperationException());
  7.  
  8.    //exercise
  9.    Assert.Throws<InvalidOperationException>(() => order.Fill(wareHouse));
  10.    // it will assert first and second setup.
  11.    Mock.Assert(wareHouse);

Here, we have created the order object, created the mock of IWarehouse , then I setup our HasInventory and Remove calls of IWarehouse with my expected, which is called by the order.Fill internally. Now both of these setups are marked as “MustBeCalled”. There is one additional IWarehouse.Remove that is invalid and is not marked.   On line 9 ,  as we do order.Fill , the first and second setups will be invoked internally where the third one is left  un-invoked. Here, Mock.Assert will pass successfully as  both of the required ones are called as expected. But, if we marked the third one as must then it would fail with an  proper exception. Here, we can also see that I have used the same call for two different setups, this feature is called sequential mocking and will be covered later on.

Moving forward, let’s say, we don’t want this must call, when we want to do it specifically with lamda. For that let’s consider the following code:

  1. //setup - data
  2. var order = new Order(TALISKER, 50);
  3. var wareHouse = Mock.Create<IWarehouse>();
  4.  
  5. Mock.Arrange(() => wareHouse.HasInventory(TALISKER, 50)).Returns(true);
  6.  
  7. //exercise
  8. order.Fill(wareHouse);
  9.  
  10. //verify state
  11. Assert.True(order.IsFilled);
  12. //verify interaction
  13. Mock.Assert(()=> wareHouse.HasInventory(TALISKER, 50));

 

Here, the snippet shows a case for successful order, i haven’t used “MustBeCalled” rather i used lamda specifically to assert the call that I have made, which is more justified for the cases where we exactly know the user code will behave. But, here goes a question that how we are going assert a mock call if we don’t know what item a user code may request for. In that case, we can combine the matchers with our assert calls like we do it for arrange:

  1. //setup - data
  2.  var order = new Order(TALISKER, 50);
  3.  var wareHouse = Mock.Create<IWarehouse>();
  4.  
  5.  Mock.Arrange(() => wareHouse.HasInventory(TALISKER, Arg.Matches<int>( x => x <= 50))).Returns(true);
  6.  
  7.  //exercise
  8.  order.Fill(wareHouse);
  9.  
  10.  //verify state
  11.  Assert.True(order.IsFilled);
  12.  
  13.  //verify interaction
  14.  Mock.Assert(() => wareHouse.HasInventory(Arg.Any<string>(), Arg.Matches<int>(x => x <= 50)));

 

Here, i have asserted a mock call for which i don’t know the item name,  but i know that number of items that user will request is less than 50.  This kind of expression based assertion is now possible with JustMock. We can extent this sample for properties as well, which will be covered shortly [in other posts].

In addition to just simple assertion, we can also use filters to limit to times a call has occurred or if ever occurred. Like for the first test code, we have one setup that is never invoked. For such, it is always valid to use the following assert call:

  1. Mock.Assert(() => wareHouse.Remove(Arg.Any<string>(), 100), Occurs.Never());

Or ,for warehouse.HasInventory we can do the following:

  1. Mock.Assert(() => wareHouse.HasInventory(Arg.Any<string>(), 0), Occurs.Once());

Or,  to be more specific, it’s even better with:

  1. Mock.Assert(() => wareHouse.HasInventory(Arg.Any<string>(), 0), Occurs.Exactly(1));

 

There are other filters  that you can apply here using AtMost, AtLeast and AtLeastOnce but I left those to the readers. You can try the above sample that is provided in the examples shipped with JustMock.Please, do check it out and feel free to ping me for any issues.

 

Enjoy!!

Posted: Apr 19 2010, 03:57 PM by mehfuzh | with 1 comment(s) |
Filed under: , , ,
Doing your first mock with JustMock

In this post, i will start with a  more traditional mocking example that  includes a fund transfer scenario between two different currency account using JustMock.Our target interface that we will be mocking looks similar to:

  1. public interface ICurrencyService
  2. {
  3.     float GetConversionRate(string fromCurrency, string toCurrency);
  4. }

Moving forward the SUT or class that will be consuming the  service and will be invoked by user [provided that the ICurrencyService will be passed in a DI style] looks like:

  1. public class AccountService : IAccountService
  2. {
  3.     private readonly ICurrencyService currencyService;
  4.  
  5.     public AccountService(ICurrencyService currencyService)
  6.     {
  7.         this.currencyService = currencyService;
  8.     }
  9.  
  10.     #region IAccountService Members
  11.  
  12.     public void TransferFunds(Account from, Account to, float amount)
  13.     {
  14.         from.Withdraw(amount);
  15.         float conversionRate = currencyService.GetConversionRate(from.Currency, to.Currency);
  16.         float convertedAmount = amount * conversionRate;
  17.         to.Deposit(convertedAmount);
  18.     }
  19.  
  20.     #endregion
  21. }

As, we can see there is a TransferFunds action implemented from IAccountService  takes in a source account from where it withdraws some money and a target account to where the transfer takes place using the provided conversion rate.

Our first step is to create the mock. The syntax for creating your instance mocks is pretty much same and  is valid for all interfaces, non-sealed/sealed concrete instance classes. You can pass in additional stuffs like whether its an strict mock or not, by default all the mocks in JustMock are loose, you can use it as default valued objects or stubs as well.

  1. ICurrencyService currencyService = Mock.Create<ICurrencyService>();

Using JustMock, setting up your expectations and asserting them always goes with Mock.Arrang|Assert and this is pretty much same syntax no matter what type of mocking you are doing. Therefore,  in the above scenario we want to make sure that the conversion rate always returns 2.20F when converting from GBP to CAD. To do so we need to arrange in the following way:

  1. Mock.Arrange(() => currencyService.GetConversionRate("GBP", "CAD")).Returns(2.20f).MustBeCalled();

Here, I have additionally marked the mock call as must. That means it should be invoked anywhere in the code before we do Mock.Assert, we can also assert mocks directly though lamda expressions  but the more general Mock.Assert(mocked) will assert only the setups that are marked as "MustBeCalled()”.

Now, coming back to the main topic , as we setup the mock, now its time to act on it. Therefore, first we create our account service class and create our from and to accounts respectively.

  1. var accountService = new AccountService(currencyService);
  2.  
  3. var canadianAccount = new Account(0, "CAD");
  4. var britishAccount = new Account(0, "GBP");

Next, we add some money to the GBP  account:

  1. britishAccount.Deposit(100);

Finally, we do our transfer by the following:

  1. accountService.TransferFunds(britishAccount, canadianAccount, 100);

Once, everything is completed, we need to make sure that things were as it is we have expected, so its time for assertions.Here, we first do the general assertions:

  1. Assert.Equal(0, britishAccount.Balance);
  2. Assert.Equal(220, canadianAccount.Balance);

Following, we do our mock assertion,  as have marked the call as “MustBeCalled” it will make sure that our mock is actually invoked. Moreover, we can add filters like how many times our expected mock call has occurred that will be covered in coming posts.

  1. Mock.Assert(currencyService);

So far, that actually concludes our  first  mock with JustMock and do stay tuned for more.

Enjoy!!

Posted: Apr 13 2010, 10:43 PM by mehfuzh | with 6 comment(s) |
Filed under: , , ,
JustMock is here !!

As announced earlier by Hristo Kosev at Telerik blogs , we have started giving out JustMock builds from today. This is the first of early builds before the official Q2 release and we are pretty excited to get your feedbacks.

image

Its pretty early to say anything on it. It actually depends on your feedback. To add few, with JustMock we tried to build a mocking tool with simple and intuitive syntax as possible excluding more and more noises and avoiding any smell that can be made to your code [We are still trying everyday] and we want to make the tool even better with your help. JustMock can be used to mock virtually anything. Moreover, we left an option open that it can be used to reduce / elevate the features  just though a single click. We tried to make a strong API and make stuffs fluent and guided as possible so that you never have the chance to get de-railed. Our syntax is AAA (Arrange – Act – Assert) , we decided to stay away from Record – Reply model where you record your mock first , then reply and verify them. This is quite unnatural (like gotos in c/c++) and does not conform to the right flow. Thus, AAA syntax is the right one to choose. Also, having two different syntaxes is even more confusing so we decided to keep with one and only one.

Currently, here are the things you can do with JustMock ( will cover more in-depth in coming days)

Proxy mode

  1. Mock interfaces and classes with virtual methods
  2. Mock properties that includes indexers
  3. Set raise event for specific calls
  4. Use matchers to control mock arguments
  5. Assert specific occurrence of a mocked calls.
  6. Assert using matchers
  7. Do recursive mocks
  8. Do Sequential mocking ( same method with argument returns different values or perform different tasks)
  9. Do strict mocking (by default and i prefer loose , so that i can use it as stubs)

Elevated mode

  1. Mock static methods
  2. Mock final methods
  3. Mock sealed classes
  4. Mock Extension methods
  5. Partially mock a  class member directly using Mock.Arrange
  6. Mock MsCorlib (we will support more and more members in coming days) , currently we support FileInfo, File and DateTime.

These are few, you need to take a look at the test project that is provided with the build to find more [Along with the document]. Also, one of the features that I will be using it for my next OS projects is the ability to run it separately in  proxied mode which makes it easy to redistribute and do some personal development in a more DI model and my option to elevate as i go.

I’ve surely forgotten tons of other features to mention that i will cover time but  don’t for get the URL : www.telerik.com/justmock

Finally a little mock code:

 

  1. var lvMock = Mock.Create<ILoveJustMock>();
  2.  
  3.  // set your goal
  4.  Mock.Arrange(() => lvMock.Response(Arg.Any<string>())).Returns((int result) => result);
  5.  
  6.  //perform
  7.  string ret =  lvMock.Echo("Yes");
  8.  
  9.  Assert.Equal(ret, "Yes");
  10.  // make sure everything is fine
  11.  Mock.Assert(() => lvMock.Echo("Yes"), Occurs.Once());

 

Hope that helps to get started,  will cover if not :-).

Posted: Apr 12 2010, 10:18 PM by mehfuzh | with 4 comment(s) |
Filed under: , ,
More Posts