Auto Mocking using JustMock

Auto mocking containers are designed to reduce the friction of keeping unit test beds in sync with the code being tested as systems are updated and evolve over time.


This is one sentence how you define auto mocking. Of course this is a more or less formal. In a more informal way auto mocking containers are nothing but a tool to keep your tests synced so that you don’t have to go back and change tests every time you add a new dependency to your SUT or System Under Test.


In Q3 2012 JustMock is shipped with built in auto mocking container. This will help developers to have all the existing fun they are having with JustMock plus they can now mock object with dependencies in a more elegant way and without needing to do the homework of managing the graph.


If you are not familiar with auto mocking then I won’t go ahead and educate you rather ask you to do so from contents that is already made available out there from community as this is way beyond the scope of this post.


Moving forward, getting started with Justmock auto mocking is pretty simple. First, I have to reference Telerik.JustMock.Container.DLL from the installation folder along with Telerik.JustMock.DLL (of course) that it uses internally and next I will write my tests with mocking container. It’s that simple!


In this post first I will mock the target with dependencies using current method and going forward do the same with auto mocking container.


In short the sample is all about a report builder that will go through all the existing reports, send email and log any exception in that process.


This is somewhat my  report builder class looks like:



Reporter class depends on the following interfaces:


  • IReporBuilder: used to  create and get the available reports
  • IReportSender: used to send the reports
  • ILogger: used to log any exception.

Now, if I just write the test without using an auto mocking container it might end up something like this:



Now, it looks fine. However, the only issue is that I am creating the mock of each dependency that is sort of a grunt work and if you have ever changing list of dependencies then it becomes really hard to keep the tests in sync. The typical example is your ASP.NET MVC controller where the number of service dependencies grows along with the project.


The same test if written with auto mocking container would look like:



Here few things to observe:


  • I didn’t created mock for each dependencies
  • There is no extra step creating the Reporter class and sending in the dependencies
  • Since ILogger is not required for the purpose of this test therefore I can be completely ignorant of it. How
  • cool is that ?

Auto mocking in JustMock is just released and we also want to extend it even further using profiler that will let me resolve not just interfaces but concrete classes as well. But that of course starts the debate of code smell vs. working with legacy code. Feel free to send in your expert opinion in that regard using one of telerik’s official channels.


Hope that helps


Mscorlib mocking minus the attribute

Mocking .net framework members (a.k.a. mscorlib) is always a daunting task. It’s the breed of static and final methods and full of surprises. Technically intercepting mscorlib members is completely different from other class libraries. This is the reason it is dealt differently. Generally, I prefer writing a wrapper around an mscorlib member (Ex. File.Delete(“abc.txt”)) and expose it via interface but that is not always an easy task if you already have years old codebase.

While mocking mscorlib members first thing that comes to people’s mind is DateTime.Now. If you Google through, you will find tons of example dealing with just that. May be it’s the most important class that we can’t ignore and I will create an example using JustMock Q2 with the same.

In Q2 2012, we just get rid of the MockClassAtrribute for mocking mscorlib members. JustMock is already attribute free for mocking class libraries. We radically think that vendor specific attributes only makes your code smelly and therefore decided the same for mscorlib.

Now, I want to fake DateTime.Now for the following class:

public class NestedDateTime
{
    public DateTime GetDateTime()
    {
        return DateTime.Now;
    }
}


It is the simplest one that can be. The first thing here is that I tell JustMock “hey we have a DateTime.Now in NestedDateTime class that we want to mock”.



To do so, during the test initialization I write this:



.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }



Mock.Replace(() => DateTime.Now).In<NestedDateTime>(x => x.GetDateTime());.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }


I can also define it for all the members in the class, but that’s just a waste of extra watts.



Mock.Replace(() => DateTime.Now).In<NestedDateTime>();


Now question, why should I bother doing it? The answer is that I am not using attribute and with this approach, I can mock any framework members not just File, FileInfo or DateTime. Here to note that we already mock beyond the three but when nested around a complex class, JustMock was not intercepting it correctly. Therefore, we decided to get rid of the attribute altogether fixing the issue.



Finally, I write my test as usual.



[TestMethod]
public void ShouldAssertMockingDateTimeFromNestedClass()
{
    var expected = new DateTime(2000, 1, 1);

    Mock.Arrange(() => DateTime.Now).Returns(expected);

    Assert.Equal(new NestedDateTime().GetDateTime(), expected);
}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

That’s it, we are good. Now let me do the same for a random one, let’s say I want mock a member from DriveInfo:



Mock.Replace<DriveInfo[]>(() => DriveInfo.GetDrives()).In<MsCorlibFixture>(x => x.ShouldReturnExpectedDriveWhenMocked());


Moving forward, I write my test:



[TestMethod]
public void ShouldReturnExpectedDriveWhenMocked()
{
    Mock.Arrange(() => DriveInfo.GetDrives()).MustBeCalled();

    DriveInfo.GetDrives();

    Mock.Assert(()=> DriveInfo.GetDrives());
}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Here is one convention; you have to replace the mscorlib member before executing the target method that contains it. Here the call to DriveInfo is within the MsCorlibFixture therefore it should be defined during test initialization or before executing the test method.





Hope this gives you the idea.

Writing ASP.NET MVC bootstrapper with Autobox

This will post will show how you can use AutoBox to easily write a bootstrapper for ASP.NET MVC. I have used the latest version of AutoBox (available from nuget, this version also includes Castle.Windsor internally for managing dependencies rather using its own resolver and does not require interface to type naming convention [IAccountRepository –> AccountRepository]) . To understand what is AutoBox , how you can use it for caching using memcached and let it automatically handle dependencies for controllers and repositories, i would recommend to take a look at this post:

http://weblogs.asp.net/mehfuzh/archive/2011/11/06/introducing-autobox-on-the-fly-dependency-injection-and-caching-container.aspx

Moving forward , let’s consider a simple bootstrapper interface:

  1. public interface IBootStrapperTask
  2. {
  3.     void Execute();
  4. }

The Execute()  method will be invoked during initialization for registering routes, controllers, mappings (AutoMapper), etc. We will have one static factory (Ex. BootStrapper)  that will initiate it through CommonServiceLocator.

  1. public static class BootStrapper
  2. {
  3.     /// <summary>
  4.     /// Executes registered tasks.
  5.     /// </summary>
  6.     public static void Execute()
  7.     {
  8.         ServiceLocator.Current.GetAllInstances<IBootStrapperTask>().ToList().ForEach(task =>task.Execute());
  9.     }
  10. }

A typical example of a bootstrapping task could be RegisterRoutes:

  1. public class RegisterRoutes : IBootStrapperTask
  2. {
  3.     private readonly RouteCollection routes;
  4.  
  5.     /// <summary>
  6.     /// Intializes the new instance of <see cref="RegisterRoutes"/> class.
  7.     /// </summary>
  8.     public RegisterRoutes()
  9.         : this(RouteTable.Routes)
  10.     {
  11.         // intentionally left blank.
  12.     }
  13.  
  14.     /// <summary>
  15.     /// Intializes the new instance of <see cref="RegisterRoutes"/> class.
  16.     /// </summary>
  17.     internal RegisterRoutes(RouteCollection routes)
  18.     {
  19.         this.routes = routes;
  20.     }
  21.  
  22.     public void Execute()
  23.     {
  24.         routes.Clear();
  25.  
  26.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  27.         routes.IgnoreRoute("{*favicon}", new {favicon = @"(.*/)?favicon.ico(/.*)?"});
  28.  
  29.         Routes.Register(routes);
  30.     }
  31.  
  32. }

Here on line 29, i have added Routes.Register which is similar to the BootStrapper.Execute() that further narrows down to specific routing classes. For example. AccountRoutes.

  1. public static void Register(RouteCollection routes)
  2. {
  3.     ServiceLocator.Current.GetAllInstances<IRoutesRegistration>().ToList()
  4.        .ForEach(task => task.Register(routes));
  5. }

The code inside Routes class again pretty straight forward and exactly identical to BootStrapper except the IRoutesRegistration interface. We can also have RegisterControllers but since the dependencies are automatically wired by AutoBox, we only need to specify (if required) what repository methods to be data cached and for what duration.

  1. public class RegisterControllers : IBootStrapperTask
  2. {
  3.     void IBootStrapperTask.Execute()
  4.     {
  5.         Container.Setup<ProductRepository>(x => x.GetProductDetails(0)).Caches(TimeSpan.FromMinutes(1)).VaryByArgs();
  6.         ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
  7.     }
  8. }

More on caching and how MyControllerFactory should look like; please check my previous post as well as the product documentation. Finally, it’s about gluing the whole thing together and we just need to have these lines in global.asax.cs

  1. protected void Application_Start()
  2. {
  3.     // Initalizes autobox self.
  4.     Container.Init();
  5.     BootStrapper.Execute();
  6. }

When you will run the project; if you followed the flow then it should work as you have expected it. The project page for AutoBox can be reached here: http://mehfuzh.github.com/AutoBox/ .

 

Hope that helps

Assert the order of expected calls over instances

How you assert through unit test that an user is authenticated before doing withdraw operation? You can surely verify a method is invoked as expected but if you want to ensure the order right then you might require a little more. JustMock lets you specify the order in which your setups should be executed. This helps you identify the exact way in which a particular logic is implemented.

To begin, lets consider the following context:

User wants to withdraw money from his account. Withdraw operation should validate the following goals:

  • It should check if the user is authenticated
  • It should get the balance for the authenticated user and check if the amount to be withdrawn is less than or equals to what is specified.
  • Do the withdraw operation and return the remaining balance.

Now we have one IUserService interface

  1. public interface IUserSerivce
  2. {
  3.     bool IsAuthenticated { get; }
  4.     IUser GetUser();
  5.  
  6. }

One IAccountService interface to process the accounts operation:

  1. public interface IAccountService
  2. {
  3.     double Withdraw(double amount);
  4.     double GetBalance(IUser user);
  5. }

The basic AccountRepository class with minimal implementation covering the above context looks like:

  1. public class AccountRepsotory
  2.      {
  3.          public AccountRepsotory(IUserSerivce userService, IAccountService accountService)
  4.          {
  5.              this.userService = userService;
  6.              this.accountService = accountService;
  7.          }
  8.  
  9.          public virtual double Withdraw(double amount)
  10.          {
  11.              if (userService.IsAuthenticated)
  12.              {
  13.                  if (accountService.GetBalance(userService.GetUser()) >= amount)
  14.                  {
  15.                      return accountService.Withdraw(amount);
  16.                  }
  17.              }
  18.  
  19.              throw new ArgumentException("TODO");
  20.          }
  21.  
  22.          private readonly IUserSerivce userService;
  23.          private readonly IAccountService accountService;
  24.      }

Ensuring every step to be executed in an orderly manner , we just need to specify an extra InOrder option in Mock.Arrange that will otherwise fail the test during assert for any change of the expected execution order.

  1. [TestMethod]
  2. public void ShouldCheckUserAndBalanceInOrderWhenSpecificAmountIsWithdrawn()
  3. {
  4.     var userService = Mock.Create<IUserSerivce>();
  5.     var accountService = Mock.Create<IAccountService>();
  6.     
  7.     var user = Mock.Create<IUser>();
  8.  
  9.     Mock.Arrange(() => userService.IsAuthenticated).Returns(true).InOrder();
  10.     Mock.Arrange(() => userService.GetUser()).Returns(user).InOrder();
  11.     Mock.Arrange(() => accountService.GetBalance(user)).Returns(1000).InOrder();
  12.  
  13.     Mock.Arrange(() => accountService.Withdraw(Arg.AnyDouble)).Returns((amount) => 1000 – amount).InOrder();
  14.  
  15.  
  16.     var repository = new AccountRepsotory(userService, accountService);
  17.  
  18.     Assert.AreEqual(990, repository.Withdraw(10));
  19.  
  20.     Mock.Assert(userService);
  21.     Mock.Assert(accountService);
  22. }

Let’s remove the line# 13 from AccountRepository.Withdraw  that yields:

  1. public virtual double Withdraw(double amount)
  2. {
  3.     if (userService.IsAuthenticated)
  4.     {
  5.         return accountService.Withdraw(amount);
  6.     }
  7.  
  8.     throw new ArgumentException("TODO");
  9. }

 

Since we broke the order, the test will fail with the following message:

image

 

Here one thing to notice that InOrder is applied to different mock instances within the test method scope that makes it effective in most practical and wide variety of scenarios. I have used Q3 SP build for the purpose (Also available via NuGet).

 

Hope that helps

Asserting a mock with test framework

When asserting an expected call for its number of occurrences or may be just to verify if the setup/arrange is acted as intended, the tool generally raises assertion that points us to the reason why the test failed. Different mocking tools use different exception classes therefore there is no common way to consolidate them.

However, if we just take a look into the test framework unless its some alien one, they all have a common underlying structure for Assert.Throws or ExpectedException (MSTest).

  • MS Test (C# and Silverlight)
    • Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException
  • NUnit
    • NUnit.Framework.AssertionException
  • XUnit
    • Xunit.Sdk.AssertException
  • MSpec
    • Machine.Specifications.SpecificationException
  • MbUnit
    • Gallio.Framework.Assertions.AssertionException

So the point here is that if we just use the existing exception class rather than thinking one of our own, it greatly increases the scope of the tooling support. For example, let’s consider the “Test Results” window inside visual studio 2010 that tells us that Foo.Echo() is never invoked as it is expected. Since, its just one line and shows only the reason rather the whole stack trace, it is definitely more user-friendly:

 

image

 

Comparing to the one below, for which you even need to expand and see what’s going wrong.

 

image

 

Here I mentioned the word “increased tooling support”, of course it means the tool vendors (who are creating runners) never need to know which mocking tool and update their formatting code over considering  a test framework.

Technically , JustMock dynamically probes the underlying framework which is the idea very much got from this  project at codeplex which I would like to point here:

http://fluentassertions.codeplex.com/

 

The feature is available from Q3 2011 in JustMock Free as well as in commercial edition.

Hope that helps

Future mocking with #IgnoreInstance

In my previous post, i showed how JustMock picks mock expectations based on current context without the instance being injected. Based on feedback we found that It’s sometimes confusing and often does not work as intended. However, the context of this post is not to introduce future mocking rather a new feature that allows you to skip mock instance intentionally (when you can’t pass the dependency through a constructor or via method argument) instead the tool is applying it for you on behalf.

You can find more on future mocking and some abstract behind it from my previous post:

http://weblogs.asp.net/mehfuzh/archive/2011/09/30/future-mocking-revisited.aspx

Now moving forward, i will represent a code block that fails and then solve it with IgnoreInstance  modifier. I am of course thankful to Lior Friedman for pointing me this. So the code that is very much similar to what he showed me:

Code that fails

  1. var fakeUsed = Mock.Create<UsedClass>();
  2.  
  3. Mock.Arrange(() => fakeUsed.ReturnFive()).Returns(7);
  4.  
  5. Assert.AreEqual(7, fakeUsed.ReturnFive());    
  6.  
  7. Assert.AreEqual(5, new UsedClass().ReturnFive());

Now , if the context resolve is implicit then both of the calls will return the same value. In this typical use case the search by context wont work because for some arrange I might want to ignore instance and for some other I want to execute the call as it is.  Taking this into account, introduced more explicit ignoreInstance switch. This will not only let you ignore instance per setup for the same type also make it more pragmatic and to the point since now I know what I am doing, not the tool getting on my  way.

Therefore only when you want to apply a particular setup for all instance, you will do it like:

  1. var fakeUsed = Mock.Create<UsedClass>();
  2.  
  3. Mock.Arrange(() => fakeUsed.ReturnFive()).Returns(7).IgnoreInstance();
  4.  
  5. Assert.AreEqual(7, fakeUsed.ReturnFive());    
  6.  
  7. Assert.AreEqual(7, new UsedClass().ReturnFive());

 

This is a new feature and available from Q3 2011 build and removes the implicit context search approach.

 

Hope that helps

 

P.S. We are gathering next cool feature for JustMock. Since we believe it’s a tool worth when there is a personal touch therefore please send me / us your ideas in the forum or via email or just a tweet.

Introducing AutoBox – On the fly dependency injection and caching container.

Just when we have dependencies for a controller, we need to wrap around our heads to write a bootstrapper that will dynamically inject dependencies for a controller in runtime and once we we want to do  data caching like a particular method in accounts repository need to get cached for a  certain number of time and it should invalidate when someone calls update, things get complex and may be we get around this with some attribute based solution.

AutoBox

Therefore, I introduce to you AutoBox. It is a on the fly dependency injection and caching container. It dynamically injects dependencies based on convention. Also, let you cache repository calls to memcached (the most popular cross-platform caching system) which is originally implemented by LiveJournal and used by high volume site like Youtube.

Now getting started with AutoBox is simple.  Lets consider that you have a ProductController and the constructor looks something like:

 

  1. public ProductController(IProductRepository repository)
  2. {
  3.     this.repository = repository;
  4. }

ProductRepository is implemented in MyCoolWebSite.Repository folder where IProductRepository is under MyCoolWebSite.Repository.Abstraction (Not a required). In the global.ascx you first need to add the following line:

 

  1. Container.Init();

Here to mention that AutoBox is a convention based tool, it means IProductRepository will search for ProductRepository class that implements it (although will support custom mappings based on feedback in later releases).

Next you need to override the GetControllerInstance from DefaultControllerFactory. Since AutoBox is implemented using CommonServiceLocator, therefore you can directly include ServiceLocator.Current.GetInstance that will return the target controller with dependencies properly injected.

 

  1. public class CustomControllerFactory : DefaultControllerFactory
  2. {
  3.     protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
  4.     {
  5.         return ServiceLocator.Current.GetInstance(controllerType) as IController;
  6.     }
  7. }

 

Finally, at the end of global.ascx.cs you need to write the following line; so that all the controller get instance requests go through AutoBox:

 

  1. ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());

 

Hit F5 and and you are ready to roll with dependencies.

 

Now, moving forward there is a method in IProuductRepository lets say IProductReposiroty.GetAllProducts(). You just dont want to hit database all the time, unless invalidated. Therefore, you can further specify (you can also combine that with your bootstrapper that registers routes and mappings using AutoMapper):

 

  1. Container.Setup<ProductRepository>(x => x.GetAllProducts()).Caches(TimeSpan.FromMinutes(1));

 

This tells AutoBox to cache the result of the call (using memcached) that will automatically invalidate after a minute. However you can explicitly specify the method that will invalidate it.

  1.  
  2. Container.Setup<ProductRepository>(x=> x.Create(Arg.Varies<Product>()).Invalidates(x => x.GetAllProducts());

 

You will notice here that I have used Arg.Varies{T}. Its similar to VaryByParams in output cache where it tells the tool to invalidate  based on the variable argument value. Finally to make Memcached working you will need to have the following block in web.config (will be added automatically when installed from NuGet [Yes its NuGet]).

 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3.  
  4.   <configSections>
  5.     <section name="autoBox" type="AutoBox.AutoBoxSection, AutoBox" />
  6.   </configSections>
  7.  
  8.   <autoBox cacheStore="localhost" cacheProvider="MemcachedProvider" />
  9.  
  10. </configuration>

 

Here you will notice that by default its pointing to localhost and MemcachedProvider. However it can be an external IP pointing to Amazon ElastiCache (released a few weeks ago).Here to note that memcached is a caching mechanism and therefore the tool is agnostic of any underlying cloud service that you may use.

To test caching locally, you can use the CouchBase’s Membase server (Not limited to), it gives you a nice web based GUI to monitor the cache usage, configure memory and clusters.

You can download it from this link:

http://www.couchbase.com/products-and-services/memcached/

 

You can get more information on this project, download source and contribute at the following URL:

http://mehfuzh.github.com/AutoBox/

 

As mentioned above, it is also possible to use the tool with a hand-rolled bootstrapper that uses IOC container (Ex. Ninject) and AutoMapper  and can save you some lines in binding the controller dependencies and if you want to use high-performance caching mechanism like memcached and don’t  want to pull your hair off on how to invalidate a repository call when saved a part of it then this tool can give you a boost.

 

Hope that helps

Future mocking revisited

Previously , I have posted how it is possible to mock a method without passing the dependency through a constructor / calling method. This is something true for third party controls and tools where we have little control over how its created.

You can find more on that in the following post:

http://weblogs.asp.net/mehfuzh/archive/2011/07/21/fake-a-member-without-worrying-about-passing-the-dependency.aspx

 

Now the feature that lets you mock  members without passing the dependency, we call it Future mocking. However it does not mean that Justmock ignores the instance completely but rather there is a workflow where it checks if there is no match for instance (of course it is a profiler intensive feature) and mocked within current context it tries to match any setup that is meant for.

One of the best example that I recently encountered through a community feedback that describes a UI case where based on some action against the form, raises an event which needs to be handled in a specific way in the unit test to assert the expected value.

Therefore, we have a Form class where the constructor looks something like:

 

  1.  
  2. public Form2()
  3. {
  4.     InitializeComponent();
  5.  
  6.     this.service = new EntryService();
  7.  
  8.     service.Saved += new EventHandler<EntrySavedEventArgs>(service_Saved);
  9. }            

 

We have a SaveToDatabase method that on the other hand invokes the Save method in EntryService and finally raise an event when successfully saved.

 

  1. public void SaveToDatabase(string value)
  2.     {
  3.         try
  4.         {
  5.             this.service.Save(value);
  6.         }
  7.         catch (DuplicateEntryException ex)
  8.         {
  9.             MessageBox.Show("Entry Duplicated " + ex.DuplicatedValue);
  10.         }
  11.         catch (ArgumentNullException)
  12.         {
  13.             this.label1.Text = "Valeur manquante";
  14.         }
  15.     }

 

Here  for now lets consider our event target will have just the following block:

 

  1. void service_Saved(object sender, EntrySavedEventArgs e)
  2. {
  3.     this.label1.Text = "Saved string : " + e.EntryValue;
  4. }

 

In the first snippet we can see that EntryService is created in  the constructor of Form2 class and therefore not injected via some external class/agent. The thing that the particular user wanted to do is to raise the target event with the expected EntryValue that is passed during SaveToDatabase call. So the specification for it that verifies such follows:

 

  1. [Subject(typeof(Form2))]
  2. public class when_save_to_database_is_invoked_on_form
  3. {
  4.     Establish context = () =>
  5.     {
  6.         IEntryService serviceMock = Mock.Create<EntryService>();
  7.         Mock.Arrange(() => serviceMock.Save(valueToSave)).Raises(() => serviceMock.Saved += null, new EntrySavedEventArgs(valueToSave));
  8.         sut = new Form2();         
  9.     };
  10.  
  11.     private Because of = () =>
  12.     {
  13.         sut.SaveToDatabase(valueToSave);
  14.     };
  15.  
  16.     private It should_assert_that_label_contains_expected_valueToSave = () =>
  17.         sut.label1.Text.ShouldEqual("Saved string : " + valueToSave);
  18.  
  19.  
  20.     static Form2 sut;
  21.     const string valueToSave = "Raise Event";
  22. }

Here we can see that although no instance is supplied to the target UI class JM picks up the intended setup from the context. Needless to mention that in code there are smells like labe1 is private and is accessed by specifying InternalsVIsibleTo  for specification assembly but rather it should be implemented using MVVM and {Binding Label1 } way. But that is out of the scope of this post and leave that to the reader. I would further thank Vincent Grondin for the project and you can try this out with the latest release as of today.

You can further download the sample project here:

 

Finally, hope this has given you an idea on getting started with future mocking.

Thanks

PostSharp and JustMock side by side.

In this post I will show mocking a member call inside a postsharp aspect. There were previously compatibility issues between both of the tools running side by side which is now been officially fixed with the most recent release of that tool (>= 2.1.2.8-1594). For those who don’t know what PostSharp is all about, it is a tool that lets you write aspects easily than you can imagine.

Personally , it took me just minutes to get started with a aspect that will authorize a call before invoking it. Consider that you want to authorize an asp.net MVC controller action and if you ever look into the code you will see that it validates the currently logged in user’s identity.

In the simplest way I have an Identity class that has a IsAuthenticated property which is not implemented for sure:

 

  1. public class Identity
  2. {
  3.     public static bool IsAuthenticated
  4.     {
  5.         get
  6.         {
  7.             throw new NotImplementedException("Mimic the code User.Identity.IsAuthenticated");
  8.         }
  9.     }
  10. }

 

Next we have an Inventory class that places an order for an authorized user:

  1. public class Inventory
  2.  {
  3.      [Authorize]
  4.      public bool PlaceOrder(Order order)
  5.      {
  6.          orders.Add(order);
  7.          return true;
  8.      }
  9.  
  10.      public bool HasOrders()
  11.      {
  12.          return orders.Count > 0;
  13.      }
  14.  
  15.      private IList<Order> orders = new List<Order>();
  16.  }

 

Now AuthorizeAttribute is implemented on MethodInterceptionAspect where we can write useful  code during the execution of a particular action (return to login page if not authorized, etc). In this case it just skips call for invalid identity.

  1. [Serializable]
  2. public class AuthorizeAttribute : MethodInterceptionAspect
  3. {
  4.     public override void OnInvoke(MethodInterceptionArgs args)
  5.     {
  6.         if (Identity.IsAuthenticated)
  7.             base.OnInvoke(args);
  8.     }
  9. }

Here to note that SerializableAttribute is a required attribute by PostSharp. Once you compile the code it will actually write the necessary hooks inside the method based on the aspects you have declared.

 

Next is a simple test using MSpec where  I ensured that if the identity is valid then it places the order to an inventory.

 

  1. [Subject(typeof(Inventory))]
  2. public class when_authorization_ensures_a_valid_identity
  3. {
  4.     Establish context = () =>
  5.     {
  6.         Mock.Arrange(() => Identity.IsAuthenticated).Returns(true);
  7.     };
  8.  
  9.     private Because of = () =>
  10.     {
  11.         inventory = new Inventory();
  12.         inventory.PlaceOrder(new Order("Taslisker", 1) { OrderDate = DateTime.Now });
  13.     };
  14.  
  15.     private It should_assert_that_order_place_was_successful = () =>
  16.        Assert.True(inventory.HasOrders());
  17.  
  18.     static Inventory inventory;
  19. }

 

Here I have mocked the static Identity call using the Justmock that intercepts it on top the PostSharp hooks during authorization. Further I used the PostSharp starter edition for the purpose.

Please check out the project here  => 

 

Happy coding ~~

Fake a member without worrying about passing the dependency

I have came across this several times in forum (telerik) on how I can really fake an item yet I don’t want to pass the instance as an argument. Ideally, this is not a best design but there are third- partly libraries that you have little control over how its written.  Anyway, whatever the case might be. This post will show you how you can achieve the above using JustMock. I will be using MSpec in conjunction for the example.

 

So here is the sample class that I am going to use:

 

  1. public class LegacyCode
  2. {
  3.     public int CheckUser(string userName, string password)
  4.     {
  5.         var _service = new LoginService();
  6.         return _service.ValidateUser(userName, password);
  7.     }
  8. }

Here CheckUser is calling  LoginService.ValidateUser that we are going replace with a fake call. Also here is the  LoginService class that is not much significant just throws exception when ValidateUser is called that will even confirm if the correct variant is invoked.

 

  1. public class LoginService
  2. {
  3.     public int ValidateUser(string userName, string password)
  4.     {
  5.         throw new NotImplementedException("Nothing here");
  6.     }
  7. }

 

Here is the specification that I wrote with Justmock and MSpec

 

  1. [Subject(typeof(LoginService))]
  2.   public class when_a_mock_is_called_without_instance_being_injected
  3.   {
  4.       Establish context = () =>
  5.       {
  6.           service = new LoginService();
  7.           Mock.Arrange(() => service.ValidateUser(userName, password)).MustBeCalled();
  8.       };
  9.  
  10.       private Because of = () =>
  11.       {
  12.           var sut = new LegacyCode();
  13.           sut.CheckUser(userName, password);
  14.       };
  15.  
  16.       private It must_assert_that_fake_setup_is_invoked_from_context = () =>
  17.           Mock.Assert(service);
  18.  
  19.  
  20.       static LoginService service;
  21.       readonly static string userName = "User";
  22.       readonly static string password = "Pwd";
  23.   }

 

This concludes that if you have a mock setup and you cant pass the instance via dependency injection, JustMock will still try to find the closest mock setup for arguments that it will replace the original call with when invoked. There is no extra setup call to be associated in that regard and keeps the tool more out of your way.

 

In addition I am attaching the sample project to let you have a look. Also you will be needing JustMock full edition installed to try this out.