After making the post on mocking LINQ to SQL, this morning i was having a chat with Stephen forte and come to know that telerik a has product named RLINQ. RLINQ is built on top of OpenAccess and it supports variety of databases. Being curious, i thought of giving a spin with it and may be try to mock its LINQ to SQL implementation using JustMock.

 

Now, before i start, i also found that OpenAccess has a free / express version that works on top express database [Ex.sqlexpress] but supports all the features that full version offers. I will be using the free version here. The download is provided at the end of the post along with link pointing steve’s introduction of RLINQ.

 

Once you have downloaded OpenAccess Q2, you first need to create a class library project and inside the add item dialog you need to choose  “Telerik OpenAccess Domain Model” option . Actually, it looks to me same as creating an entity framework edmx just the extension is rlinq.

 image

Next, it will give you an option to choose an empty model or populating it from your database. I would rather choose to populate it from my Northwind database in SqlExpress. That prompts me up with this screen

image

Here to note that i actually first found  the “New Connection” option disabled [may be due to express version] and set my target database using the “Server Explorer” inside visual studio and found it populated as shown above.

Next, i have to choose a model name and by default it suggests “NorthwithEntityDiagram1” but i prefer to choose  “NorthwindDataContext” since things are more with data than with diagram.

image

Once everything is set. I am off to the main topic. I will use the same example from previous post. Accordingly, i created the EmployeeRepository class:

  1. public class EmployeeRepository
  2. {
  3.     public EmployeeRepository(NorthwindDataContext context)
  4.     {
  5.         this.context = context;
  6.     }
  7.  
  8.     public IQueryable<Employee> GetEmployeesByHire(DateTime frm, DateTime to)
  9.     {
  10.         return from emp in context.Employees
  11.                where emp.HireDate >= frm && emp.HireDate <= to
  12.                select emp;
  13.     }
  14.  
  15.     private readonly NorthwindDataContext context;
  16. }

This is plan and simple. There is only method that returns list of employees by hire for a date range. The goal is [those who have missed my previous post] to run the LINQ query into my fake collection to assert the expected behavior of this method.

Therefore, i will be creating a fake data context and for context.Employees i will return my custom collection and finally assert the expected behavior.

  1. [TestMethod]
  2. public void ShouldAssertGetEmployeesByHireDate()
  3. {
  4.     var context = Mock.Create<NorthwindDataContext>();
  5.     var repository = new EmployeeRepository(context);
  6.     Mock.Arrange(() => context.Employees).ReturnsCollection(GetFakeEmployees());
  7.  
  8.     var employees = repository.GetEmployeesByHire(new DateTime(2008, 1, 1), DateTime.Now);
  9.  
  10.     Assert.AreEqual(1, employees.Count());
  11.     Assert.AreEqual(3, employees.FirstOrDefault().EmployeeID);
  12. }
  13.  
  14. private static IList<Employee> GetFakeEmployees()
  15. {
  16.     return new List<Employee>
  17.     {
  18.        new Employee {EmployeeID = 1, HireDate = new DateTime(2004, 12, 1)},
  19.        new Employee {EmployeeID = 2, HireDate = new DateTime(2006, 7, 1)},
  20.        new Employee {EmployeeID = 3, HireDate = new DateTime(2009, 3, 1)}
  21.     };
  22. }

 

That’s it. As “ReturnsCollection” does a number of tasks on behalf of the developer and which is not required for all cases except for IQueryable / IEnumerable implementations, having few feedbacks from my last post, we have made this as an extension method. The reason is not to pull it up every time for mocking members where you don’t need it.  Therefore, when you need it you just have to include the following line on top your class:

  1. using Telerik.JustMock.Helpers;

The helpers extension[from SP1] also gives an opportunity to add more domain specific methods like “ReturnsCollection” without ever cluttering the core API.

 

Finally, you can check the introductory post from Steve of RLINQ here:

http://www.stephenforte.net/PermaLink,guid,734374ef-65ac-442c-a8f1-571ca9084729.aspx

The free version of OpenAccess ORM with RLINQ can be found here, there are other free and interesting tools as well:

http://www.telerik.com/community/free-products.aspx

OpenAccess version of the sample can be downloaded from:

 

Enjoy!!

Unit testing LINQ to SQL repositories can be very challenging. Unit testing such requires faking hard to mock classes and requires simulation to return your custom data for a particular LINQ statement. In this post, i will show how you can mock your LINQ repositories easily without much digging in.

As,  i was goggling [my start page is bing, its a matter of time when i will be bing-ing :-)] around, found a nice post by Ronnie Holm, where he shows how to unit test a  LINQ to SQL repository. I will follow his trail and use some of the codes from his post. Therefore, first of all we have an employee class:

  1. public class Employee
  2. {
  3.     public int ID { get; set; }
  4.     public DateTime HireDate { get; set; }
  5. }

Secondly, we have an LINQ DataContext implementation that has the Table<Employee> which we are going to mock with our expected collection.

  1. public partial class AdventureWorksDataContext : DataContext
  2. {
  3.     public AdventureWorksDataContext(string conntection): base(conntection)
  4.     {
  5.         // skip
  6.     }
  7.  
  8.     public Table<Employee> Employees
  9.     {
  10.         get
  11.         {
  12.             return GetTable<Employee>();
  13.         }
  14.     }
  15. }

Next, we have a repository that contains the LINQ query which is going to be queried on our fake collection that will let us validate the LINQ query in subsequent calls.

  1. public class EmployeeRepository
  2. {
  3.     public EmployeeRepository(AdventureWorksDataContext context)
  4.     {
  5.         this.context = context;
  6.     }
  7.  
  8.     public IQueryable<Employee> GetEmployeesByHireDate(DateTime start, DateTime end)
  9.     {
  10.         return  from e in context.Employees
  11.              where e.HireDate >= start && e.HireDate <= end
  12.              select e;
  13.     }
  14.  
  15.     private AdventureWorksDataContext context;
  16. }

Here, i have removed the ToList()  from Ronnie’s code. In ideal case, people may not be having ToList() call into their LINQ query all the time. Secondly, i added the a way to pass our faked DataContext to the repository class. As there should be a minimal dependency to keep the code structure immutable and i think its not a best practice to mock a call for future instance, where it does not have any tie with current code flow.

Finally, its all about mocking , and the steps are:

  1. Create the mock for AdventureWorksDataContext.
  2. Set the context.Employees to return the expected collection.
  3. Finally, act and assert.

 

Therefore, it becomes:

  1. [TestMethod]
  2. public void ShouldAssertGetEmployeesByHireDate()
  3. {
  4.     var context = Mock.Create<AdventureWorksDataContext>();
  5.  
  6.     Mock.Arrange(()=> context.Employees).ReturnsCollection(GetFakeEmployees());
  7.  
  8.     var repository = new EmployeeRepository(context);
  9.     var employees = repository.GetEmployeesByHireDate(new DateTime(2008, 1, 1), DateTime.Now);
  10.  
  11.     Assert.AreEqual(1, employees.Count());
  12.     Assert.AreEqual(3, employees.FirstOrDefault().ID);
  13. }
  14.  
  15.  
  16. private IList<Employee> GetFakeEmployees()
  17. {
  18.     return new List<Employee> {
  19.         new Employee { ID = 1, HireDate = new DateTime(2004, 12, 1) },
  20.         new Employee { ID = 2, HireDate = new DateTime(2006, 7, 1) },
  21.         new Employee { ID = 3, HireDate = new DateTime(2009, 3, 1) } };
  22. }

 

Here, you might like to ensure that your collection is set right, so it is possible to do

  1. IList<Employee> list = context.Employees.ToList();
  2. Assert.AreEqual(3, list.Count);

 

That’s it for today. Again special and indirect thanks goes to Ronnie, because i used his code and to him for mentioning JustMock in his post.

 

Link to the sample project  : LINQToSql001.zip 

Enjoy!!!

In this post, i will start with an MVC sample created from the default template project that is bundled with ASPNET MVC2 installation. This template provides not just a dummy project with folder organized but rather a full running app.The target of this post is to show a mocking of a controller action, in that regard i have picked  registration action chosen from the accounts controller of the provided sample that looks similar to:

  1. [HttpPost]
  2. public ActionResult Register(RegisterModel model)
  3. {
  4.     if (ModelState.IsValid)
  5.     {
  6.         // Attempt to register the user
  7.         MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
  8.  
  9.         if (createStatus == MembershipCreateStatus.Success)
  10.         {
  11.             FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
  12.             return RedirectToAction("Index", "Home");
  13.         }
  14.         else
  15.         {
  16.             ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
  17.         }
  18.     }
  19.  
  20.     // If we got this far, something failed, redisplay form
  21.     ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
  22.     return View(model);
  23. }

Here the basic workflow that can be ensured for the target action are:

  • For valid status:
    • Creates the user with membership service.
    • Validates the create status.
    • On validating , signs in the user.
    • Returns to expected action.
  • For Invalid status:
    • Raises a model error.
  • Stores the password length.
  • Return;

Accordingly, to cover the first criteria that covers a valid registration.  We first created the accounts controller  and the registration model.

  1. AccountController controller = new AccountController();
  2. RegisterModel registerModel = new RegisterModel();

In order to validate model state, we also need to mock out the ModelStateDictionary  to set our expectation:

  1. var modelState = Mock.Create<ModelStateDictionary>();

Then, according to flow, we setup:

  1. Mock.Arrange(() => modelState.IsValid).Returns(true).MustBeCalled();
  2. Mock.Arrange(() => controller.ModelState).Returns(modelState);

Next, we need to pass out our custom MembershipService to the controller and  set it to return a valid response ignoring the arguments. We are ignoring the arguments, as here the specific argument is not important and we are concerned more with the desired step that should be completed.

  1. // mock membership service
  2. var membershipService = Mock.Create<IMembershipService>();
  3. Mock.Arrange(() => membershipService.CreateUser("", "", "")).IgnoreArguments()
  4.     .Returns(MembershipCreateStatus.Success).MustBeCalled();
  5. controller.MembershipService = membershipService;

Now, after having a successful registration our next goal is to make sure that developer has written the sign in code correctly and accordingly we do:

  1. // mock auth services
  2. var formsAuthService = Mock.Create<IFormsAuthenticationService>();
  3. Mock.Arrange(() => formsAuthService.SignIn("", false)).IgnoreArguments().MustBeCalled();
  4. controller.FormsService = formsAuthService;

 

To wrap it up and give a test run, we execute the controller with the RegisterModel  object that we have created previously.

  1. // act
  2. controller.Register(registerModel);

 

Finally, we make sure that required calls are made properly.

  1. // assert
  2. Mock.Assert(modelState);
  3. Mock.Assert(membershipService);
  4. Mock.Assert(formsAuthService);

 

Now, this is of a rough test, as you can see there are three different types of assert which should spun three different test methods. I left that to the reader :-).

 

P.S. This example is done using JustMock , by the time of writing this post IgnoreArguments() is still under its way to release[Justmock still in its beta]. The way shown for ignoring arguments can also be done using matcher, but it is to mention that for two or many arguments when we just want to ignore the whole chunk, using a modifier call is more elegant and cleaner to read.

Previously, i made a post  showing how you can leverage the dependent interfaces that is implemented by JustMock during the creation of mock instance. It could be a informative post that let you understand how JustMock behaves internally for classes or interfaces implement other interfaces into it. But the question remains, how you can add your own custom interface to your target mock. In this post, i am going to show you just that.

Today, i will not start with a dummy class as usual rather i will use two most common interfaces in the .NET framework  and create a mock combining them. Before, i start i would like to point out that in the most recent release of JustMock we have extended the Mock.Create<T>(..) with support for additional settings though closure. You can add your own custom interfaces , specify directly the real constructor that should be called or even set the behavior of your mock.

Doing a fast forward directly to the point,  here goes the test code for create a creating a mock that contains the mix for ICloneable and IDisposable using the above mentioned changeset.

  1. var myMock = Mock.Create<IDisposable>(x => x.Implements<ICloneable>());
  2. var myMockAsClonable = myMock as ICloneable;
  3. bool isCloned = false;
  4.  
  5. Mock.Arrange(() => myMockAsClonable.Clone()).DoInstead(() => isCloned = true);
  6.  
  7. myMockAsClonable.Clone();
  8.  
  9. Assert.True(isCloned);

 

Here, we are creating the target mock for IDisposable and also implementing ICloneable. Finally, using the “as” to get the ICloneable reference then did the usual like arranging it, acting on it and assert if the expectation is met properly.

Similarly, you can do the same for a given class:

  1. var realItem = Mock.Create<RealItem>(x =>
  2. {
  3.     x.Implements<IDisposable>();
  4.     x.CallConstructor(() => new RealItem(0));
  5. });
  6. var iDispose = realItem as IDisposable;
  7.    
  8. iDispose.Dispose();

You can implement as many as interfaces you want. Here in this rudimentary example, i am also calling the real constructor for a given RealItem class.  This is to mention that you can implement custom interfaces only for non-sealed classes in conjunction with interfaces or less it will end up with an exception (proper). Also, this feature don’t require any profiler, if you are an agile developer or running it inside silverlight runtime feel free to try it turning off the JM add-in :-).

TIP :  Ability to  specify real constructor could be an useful productivity boost in cases for code change where you can re-factor the usage just by one click with your favorite re-factor tool.

 

That’s it for now. Here goes the link from previous post:

http://weblogs.asp.net/mehfuzh/archive/2010/04/26/working-with-multiple-interfaces-on-a-single-mock.aspx

 

Enjoy!!

In this post , i show how you can benefit from  sequential mocking feature[In JustMock] for setting up expectations with successive calls of same type.  To start let’s first consider the following dummy database and entity class.

  1. public class Person
  2. {
  3.     public virtual string Name { get; set; }
  4.     public virtual int Age { get; set; }
  5. }
  6. public interface IDataBase
  7. {
  8.     T Get<T>();
  9. }

 

Now, our test goal is to return different entity for successive calls on IDataBase.Get<T>(). By default, the behavior in JustMock is override , which is similar to other popular mocking tools. By override it means that the tool will consider always the latest user setup.

Therefore, the first example will return the latest entity every-time and will fail in line #10:

  1. Person person1 = new Person { Age = 30, Name = "Kosev" };
  2. Person person2 = new Person { Age = 80, Name = "Mihail" };
  3. var database = Mock.Create<IDataBase>();
  4. Mock.Arrange(() => database.Get<Person>()).Returns(person1);
  5. Mock.Arrange(() => database.Get<Person>()).Returns(person2);
  6. //fail
  7. Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode());
  8. Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode());

We can solve it the following way using a Queue and that removes the item from bottom on each call:

  1. Person person1 = new Person { Age = 30, Name = "Kosev" };
  2. Person person2 = new Person { Age = 80, Name = "Mihail" };
  3. var database = Mock.Create<IDataBase>();
  4. Queue<Person> queue = new Queue<Person>();
  5. queue.Enqueue(person1);
  6. queue.Enqueue(person2);
  7. Mock.Arrange(() => database.Get<Person>()).Returns(queue.Dequeue());
  8. Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode());
  9. Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode());

This will ensure that right entity is returned but this is not an elegant solution. So, in JustMock we introduced a  new option that lets you set up your expectations sequentially. Like:

  1. Person person1 = new Person { Age = 30, Name = "Kosev" };
  2. Person person2 = new Person { Age = 80, Name = "Mihail" };
  3. var database = Mock.Create<IDataBase>();
  4. Mock.Arrange(() => database.Get<Person>()).Returns(person1).InSequence();
  5. Mock.Arrange(() => database.Get<Person>()).Returns(person2).InSequence();
  6. Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode());
  7. Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode());

The  “InSequence” modifier will tell the mocking tool to return the expected result as in the order it is specified by user. The solution though pretty simple but neat and way too simpler than using a collection to solve this type of cases.

Hope that helps

P.S. The example shown in my blog is using interface don’t require a profiler  and you can even use a notepad and build it referencing Telerik.JustMock.dll, run it with GUI tools and it will work. But this feature also applies to concrete methods that includes JM profiler and can be implemented for more complex scenarios.

Writing state of art unit tests that can validate your every part of the framework is challenging and interesting at the same time, its like becoming a samurai. One of the key concept in this is to keep our test synced all the time as underlying code changes and thus breaking them to the furthest unit as possible.  This also means, we should avoid  multiple conditions embedded in a single test.

Let’s consider the following example of transfer funds.

  1. var currencyService = Mock.Create<ICurrencyService>();
  2. //// current rate
  3. Mock.Arrange(() => currencyService.GetConversionRate("AUS", "CAD")).Returns(0.88);
  4.  
  5. Account to = new Account { Currency = "AUS", Balance = 120 };
  6. Account from = new Account { Currency = "CAD" };
  7.  
  8. AccountService accService = new AccountService(currencyService);
  9.  
  10. Assert.Throws<InvalidOperationException>(() => accService.TranferFunds(to, from, 200));
  11.  
  12. accService.TranferFunds(to, from, 100);
  13.  
  14. Assert.Equal(from.Balance, 88);
  15. Assert.Equal(20, to.Balance);

At first look,  it seems ok but as you look more closely , it is actually doing two tasks in one test. At line# 10 it is trying to validate the exception for invalid fund transfer and finally it is asserting if the currency conversion is successfully made.

Here, the name of the test method itself is pretty vague. The first rule for writing unit test should always reflect to inner working of the target code, where just by looking at their names it is self explanatory. Having a obscure name for a test method not only increase the chances of cluttering the test code, but it also gives the opportunity to add multiple paths into it and eventually makes things messy as possible.

I would rater have two test methods that explicitly describes its intent and are more self-validating.

ShouldThrowExceptionForTransferringFromAccontWithNoFund
ShouldAssertTransferForExpectedConversionRate

Having, this type of breakdown also helps us pin-point reported bugs easily rather wasting any time on debugging for something more general and can minimize confusion among team members. Finally, we should always make our test F.I.R.S.T ( Fast.Independent.Repeatable.Self-Validating.Timely) [ Bob martin – Clean Code]. Only this will be enough to ensure, our test is as simple and clean as possible.

 

Hope that helps

--

Revisions:

Renamed ShouldThrowforInvalidFundsTransfer to a more specific as  “Invalid”, “Correct/Incorrect” words are vague as well [Community].

Return type for currency should be double instead of float in case for money [Community].

In this post, i will be showing how you can mock property sets with your expected values or even action using JustMock. To begin, we have a sample interface:

  1. public interface IFoo
  2. {
  3.     int Value { get; set; }
  4. }

Now,  we can create a mock that will throw on any call other than the one expected, generally its a strict mock and we can do it like:

  1. bool expected = false;
  2.  var foo = Mock.Create<IFoo>(BehaviorMode.Strict);
  3.  Mock.ArrangeSet(() => { foo.Value = 1; }).DoInstead(() => expected  = true);
  4.  
  5.  foo.Value = 1;
  6.  
  7.  Assert.True(expected);

Here , the method for running through our expectation for set is Mock.ArrangeSet , where we can directly set our expectations or can even set matchers into it like:

  1. var foo = Mock.Create<IFoo>(BehaviorMode.Strict);
  2.  
  3. Mock.ArrangeSet(() => foo.Value = Arg.Matches<int>(x => x > 3));
  4.  
  5. foo.Value = 4;
  6. foo.Value = 5;
  7.  
  8. Assert.Throws<MockException>(() => foo.Value = 3);

 

In the example, any set for value not satisfying matcher expression will throw an MockException as this is a strict mock but what will be the case for loose mocks, where we also have to assert it. Here, let’s take an interface with an indexed property. Indexers are treated in the same way as properties. As with basic, indexers let you access your class if it were an array.

  1. public interface IFooIndexed
  2. {
  3.     string this[int key] { get; set; }
  4. }

We want to  setup a value for a particular index,  we then will pass that mock to some implementer where it will be actually called. Once done, we want to assert that if it has been invoked properly.

  1. var foo = Mock.Create<IFooIndexed>();
  2.  
  3. Mock.ArrangeSet(() => foo[0] = "ping");
  4.  
  5. foo[0] = "ping";
  6.  
  7. Mock.AssertSet(() => foo[0] = "ping");

In the above example, both the values are user defined, it might happen that we want to make it more dynamic, In this example, i arranged it up for set with any value and finally checked if it is set with the one i am looking for.

  1. var foo = Mock.Create<IFooIndexed>();
  2.  
  3. Mock.ArrangeSet(() => foo[0] = Arg.Any<string>());
  4.  
  5. foo[0] = "ping";
  6.  
  7. Mock.AssertSet(() => foo[0] = Arg.Matches<string>(x => string.Compare("ping", x) == 0));

This is more or less of mocking user sets , but we can further have it to throw exception or even do our own task for a particular set , like :

  1. Mock.ArrangeSet(() => foo.MyProperty = 10).Throws(new ArgumentException());

Or

  1.  bool expected = false;
  2.  var foo = Mock.Create<IFoo>(BehaviorMode.Strict);
  3.  Mock.ArrangeSet(() => { foo.Value = 1; }).DoInstead(() => expected  = true);
  4.  
  5.  foo.Value = 1;
  6.  
  7.  Assert.True(expected);

Or call the original setter , in this example it will throw an NotImplementedExpectation

  1. var foo = Mock.Create<FooAbstract>(BehaviorMode.Strict);
  2. Mock.ArrangeSet(() => { foo.Value = 1; }).CallOriginal();
  3. Assert.Throws<NotImplementedException>(() => { foo.Value = 1; });

 

Finally, try all these, find issues, post them to forum and make it work for you :-).

Hope that helps,

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!!

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!!

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!!

More Posts Next page »