Vadim's Weblog

Never stop learning.

Archive for the ‘Rhino.Mocks’ Category

Tutorial to TDD using Rhino Mocks and SystemWrapper.

Posted by Vadim on December 4, 2008

In this post I want to introduce to SystemWrapper and demonstrate how it works with Rhino Mocks.
 
SystemWrapper is just a wrapper to .NET system resources like FileInfo, DirectoryInfo, Assembly, … .
 

Why do we need SystemWrapper?

 
Let assume that you’re writing code that creates a directory.  In your unit test you don’t want to create a directory you just want to know that Directory.CreateDirectory(@”C:\MyDir”) was called.  You cannot mock Directory because it’s a static class.  By wrapping Directory in SystemWrapper we can mock Directory object.  Whenever you use Directory, just use IDirectoryWrap interface instead.
 
 

TDD example with Rhino Mocks and SystemWrapper.

 

Goal:

Create a method that tries to create a directory.  If the directory already exists, don’t create it and return false; otherwise, create directory and return true.  Sounds simple enough.
 

Requirements:

Any unit testing framework of your choice.  (I’m using MbUnit v3 which is part of Gallio).
This example is taking advantage of .NET 3.5.  Let me know if you want an example using .NET 2.0.
 
Now we are ready to start.
 

1. Create new Class Library project and name it MockTutorial.

MockTutorial project

2. Rename Class1 to DirectoryInfoSample so your code looks like this:

   1: namespace MockTutorial
   2: {
   3:     public class DirectoryInfoSample
   4:     {
   5:     }
   6: }
 
3. Add a test class.  For simplicity we add our test class in the same file.  The name of the test class will be DirectoryInfoSampleTests.
   1: public class DirectoryInfoSampleTests
   2: {
   3: }
 

4. We need to add references to our unit test framework, Rhino Mocks, and SystemWrapper libraries.

MockTutorial ref 

5. Create our first test.  Remember that our method should try to create directory and there two possible cases (directory doesn’t exist and directory exists). It means that we’ll need two separate tests.  Let’s create the first test when directory already exists.The signature for our method under test will be  public bool TryToCreateDirectory(IDirectoryInfoWrap directory)You also will need to add using statements for your unit testing framework, Rhino Mocks, and SystemWrapper:

   1: using SystemWrapper.IO;
   2: using MbUnit.Framework;
   3: using Rhino.Mocks;
 

 Here comes the test.

   1: [Test]
   2: public void When_try_to_create_directory_that_already_exists_return_false()
   3: {
   4:     var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
   5:     directoryInfoStub.Stub(x => x.Exists).Return(true);
   6:     Assert.AreEqual(false, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));
   7: }
Line 4 creates the stub object for DirectoryInfo.
Line 5 stubs Exists property and return true that means that the directory exists.
Line 6 verifies that TryToCreateDirectory method returns false that means that directory wasn’t created because it already exists.
 

6. If you try to compile, it’s going to fail because we didn’t create TryToCreateDirectory method.

Let’s create the method that is going to satisfy our test.

   1: public bool TryToCreateDirectory(IDirectoryInfoWrap directory)
   2: {
   3:     return false;
   4: }
You just can see that we wrote minimum code to make our test pass successfully.
 

7. Next we want to create our second test that expects that directory doesn’t exists and creates it.

   1: [Test]
   2: public void When_try_to_create_directory_that_does_not_exist_return_true()
   3: {
   4:     var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
   5:     directoryInfoStub.Stub(x => x.Exists).Return(false);
   6:     Assert.AreEqual(true, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));
   7: }
 
You can see our second test looks very similar to the first one.  The only difference, beside the test name, is that when we stub Exists property we return false instead of true.

If you try to run the test, it will fail because in our test we expect TryToCreateDirectory method to return true.

8. It’s time again to work on our method under test.

   1: public bool TryToCreateDirectory(IDirectoryInfoWrap directory)
   2: {
   3:     if (directory.Exists)
   4:         return false;
   5:  
   6:     return true;
   7: }

Now our tests should pass.  Wait, but how do we know if the directory was created?

 
9. Modify our test to check that Create() method was called.
 
We can change our stub to mock and create an expectation for Create. If you’re confused about Mocks and Stubs, you can read Mocks aren’t Stubs by Martin Fowler.  The last we verify that Create was executed:
   1: [Test]
   2: public void When_try_to_create_directory_that_does_not_exist_return_true()
   3: {
   4:     var directoryInfoMock = MockRepository.GenerateMock<IDirectoryInfoWrap>();
   5:     directoryInfoMock.Stub(x => x.Exists).Return(false);
   6:     directoryInfoMock.Expect(x => x.Create());
   7:     Assert.AreEqual(true, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoMock));
   8:  
   9:     directoryInfoMock.VerifyAllExpectations();
  10: }
 

It will work but I prefer to use stubs and call new method in Rhino Mocks AssertWasCalled.  Isn’t it looks cleaner?

   1: [Test]
   2: public void When_try_to_create_directory_that_does_not_exist_return_true()
   3: {
   4:     var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
   5:     directoryInfoStub.Stub(x => x.Exists).Return(false);
   6:     Assert.AreEqual(true, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));
   7:  
   8:     directoryInfoStub.AssertWasCalled(x => x.Create());
   9: }
 
If you run our second test that we just modified, it will fail.  Of course, we never called Create method.

 

10. Call Create() in our TryToCreateDirectory method.

   1: public bool TryToCreateDirectory(IDirectoryInfoWrap directory)
   2: {
   3:     if (directory.Exists)
   4:         return false;
   5:  
   6:     directory.Create();
   7:     return true;
   8: }
 
11. We also can modify our first test to make sure Create() wasn’t call in case when directory already exists.

In this case we call Rhino Mocks method AssertWasNotCalled.

   1: [Test]
   2: public void When_try_to_create_directory_that_already_exists_return_false()
   3: {
   4:     var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
   5:     directoryInfoStub.Stub(x => x.Exists).Return(true);
   6:     Assert.AreEqual(false, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));
   7:  
   8:     directoryInfoStub.AssertWasNotCalled(x => x.Create());
   9: }
 
To see all the classes that wrapped by SystemWrapper follow this link.
 
More to come.  I’d like to hear from you what classes would you like to add to SystemWrapper first.
 

kick it on DotNetKicks.com

Posted in Rhino.Mocks, SystemWrapper, TDD | 7 Comments »

Mock DataTable

Posted by Vadim on June 16, 2008

Today I had to work with some legacy code.  It was originally written in Delphi and then converted line by line to C#.  Before changing anything in the code I decided to create unit tests and make sure that I have 100% coverage.

One of the thing I had to do in my unit test is to mock DataTable.  Here are the steps I made during mocking.

  1. Create needed columns in a DataTable.
  2. Create a new DataRow.
  3. Assign values to the row.
  4. Finally add the row to the DataTable.

Repeat steps 2- 4 for each row you want to add to your DataTable.

Here’s the example:

   1: [Test]
   2: public void HolidayTest()
   3: {
   4:   MockRepository mocks = new MockRepository();
   5:   ICompanyDAL dalMock = mocks.CreateMock<ICompanyDAL>();
   6:   // Create DataTable
   7:   DataTable fakeHolidays = new DataTable();
   8:   // 1. Add Columns
   9:   fakeHolidays.Columns.Add("Holiday", typeof (DateTime));
  10:   fakeHolidays.Columns.Add("Name", typeof(string));
  11:   // 2. Create new DataRow
  12:   DataRow dayRow = fakeHolidays.NewRow();
  13:   // 3. Assign values to the row
  14:   dayRow["Holiday"] = DateTime.Parse("07/04/2008");
  15:   dayRow["Name"] = "Independence Day";
  16:   // 4. Add the row to the DataTable
  17:   fakeHolidays.Rows.Add(dayRow);
  18:   _pgDate.CompanyDal = dalMock;
  19:   using (mocks.Record())
  20:   {
  21:     Expect.Call(dalMock.GetHolidays()).Return(fakeHolidays);
  22:   }
  23:   using (mocks.Playback())
  24:   {
  25:     DataTable holidays = _pgDate.Holidays;
  26:     Assert.GreaterThan(holidays.Rows.Count, 0);
  27:   }
  28: }

I used Rhino.Mocks as my mocking framework in the example above.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, MbUnit, Rhino.Mocks, TDD | Tagged: , , | 2 Comments »

The main reason to TDD; it’s not unit tests.

Posted by Vadim on September 30, 2007

I see that a lot of people using unit tests as a main selling point for TDD.  I disagree with that.  I believe that the main strength of TDD practice is that developers are forced to write loosely coupled code.

I don’t want to minimize the importance of unit tests. They’re the safety net and also a great reason to use TDD but you don’t need to follow TDD practice to create unit tests. 

I got inspired to write this after reading ‘Good practices are beyond testing’ article.  The author of this post makes a point that if we have mocking frameworks that let us to take shortcuts than what is the reason for TDD. Here’s a quote from the article.

If we don’t need DI or interfaces for testing, then why do we need them? If testing can happen without it, then that behavior isn’t driven, right? Why can’t I make a big class if its testable?

I personally switched from TypeMock to Rhino Mocks because TypeMock didn’t force me to write loosely coupled code.  I talked about this in one of my previous posts.

Unit tests are must have but it’s not the reason we TDD.

Posted in Rhino.Mocks, TDD | Leave a Comment »

TypeMock too powerful to use

Posted by Vadim on April 10, 2007

In my early stages of following TDD light I was looking for a mock object framework. I tried Rhino.Mocks and found it hard to use. Then I tried TypeMock and falled in love with the product. It allows mocking almost anything. With TypeMock I only failed to mock SqlDataReader because it doesn’t have a public constructor.

It was then. Today I believe that TypeMock is bad for the same reason I loved it before. It’s too powerful. It doesn’t force you to write a testable code.

The reason I found Rhino.Mocks hard to use is because I haven’t learn yet about Inversion of Control Containers and the Dependency Injection pattern. Today I write my own mock objects without using any framework. However, if you want to use a Mock Framework, I strongly recommend Rhino.Mocks.

If you’re not familiar with this pattern I recommend to read Jeremy Palermo’s article Simple dependency injection to get you started with unit testing.

Posted in Rhino.Mocks, TypeMock | 7 Comments »