In a previous article in this series of blog posts, I described the different Test Doubles that can be used when unit testing your application.

My favourite type of Test Double is a Mock.  Mocks are usually dynamically created by a mocking framework. Mock objects are preprogrammed with expectations which form a specification of the calls they are expected to receive.

In DotNetNuke (DNN) we use Moq (pronounced Mock-you).  To quote the creators of Moq - “Moq is designed to be a very practical, unobtrusive and straight-forward way to quickly setup dependencies for your tests. Its API design helps even novice users to fall in the "pit of success" and avoid most common misuses/abuses of mocking.”

Mocking an object that implements an interface (or class) requires less work than any of the other types of Test Double.  In fact in some cases all you have to is create the Mock and then assert that something happened.  Lets look at a real example from the unit tests created to test the new Taxonomy features in DNN 5.3.

We are going to write a test to test the code in Listing 1, the DeleteVocabulary method of the VocabularyController.

Listing 1: The DeleteVocabulary method of VocabularyController
   1:  Public Sub DeleteVocabulary(ByVal vocabulary As Vocabulary) _
   2:                                  Implements IVocabularyController.DeleteVocabulary
   3:      'Argument Contract
   4:      Requires.NotNull("vocabulary", vocabulary)
   5:      Requires.PropertyNotNegative("vocabulary", "VocabularyId", vocabulary.VocabularyId)
   6:   
   7:      _DataService.DeleteVocabulary(vocabulary)
   8:   
   9:      'Refresh Cache
  10:      DataCache.RemoveCache(_CacheKey)
  11:  End Sub

The test we are going to write is to confirm that if the method is passed valid arguments, the method will call the DeleteVocabulary method of the DataService.

All we have to do is confirm that the DataService method is called.  We are not testing the DataService here so we don’t care what it does – just that the VocabularyController calls the DataService (Listing 2)

Listing 2: Testing that the DataService’s DeleteVocabulary method is called
   1:  [Test]
   2:  public void VocabularyController_DeleteVocabulary_Calls_DataService()
   3:  {
   4:      //Arrange
   5:      Mock<IDataService> mockDataService = new Mock<IDataService>();
   6:      VocabularyController vocabularyController = new VocabularyController(mockDataService.Object);
   7:   
   8:      Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary();
   9:      vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId;
  10:   
  11:      //Act
  12:      vocabularyController.DeleteVocabulary(vocabulary);
  13:   
  14:      //Assert
  15:      mockDataService.Verify(ds => ds.DeleteVocabulary(vocabulary));
  16:  }

If we review this code we will see that it is set out using the AAA pattern.  We start off by creating a new Mock<IDataService> object that implements the IDataService interface (line 5).  We then create the VocabularyController object, giving it the mocked object (line 6).  Finally, the last part of the “Arrange” phase of the test is to create a valid Vocabulary instance (lines 8 and 9).

We are now ready to test the DeleteVocabulary method of the VocabularyController, which we do in the “Act” phase (line 12).

Finally we assert (or verify) our expectations – that the DeleteVocabulary method of the DataService was called (line 13).

Moq uses a lot of the new features introduced in C# 3 (and VB 9) and .NET 3.5 – especially the use of lambda expressions, and we will see statements like line 15 a lot when we use Moq.

Note the elegant simplicity of this code.  All we had to do was create the Mock<IDataService> object and then use it to verify that one of its methods was called.

So far so good.  This technique works really well when the Interface does not need to return any data – ie in Delete or Update scenarios.  But what about scenarios where the mocked object would be expected to return something, such as in Add or Get scenarios.

Lets first look at the GetVocabularies method in the same VocabularyController class (Listing 3)

Listing 3: The GetVocabularies method of VocabularyController
   1:  Public Function GetVocabularies() As IQueryable(Of Vocabulary) _
   2:                          Implements IVocabularyController.GetVocabularies
   3:      Return CBO.GetCachedObject(Of IQueryable(Of Vocabulary)) _
   4:                          (New CacheItemArgs(_CacheKey, _CacheTimeOut), _
   5:                                      AddressOf GetVocabulariesCallBack)
   6:  End Function
   7:   
   8:  Private Function GetVocabulariesCallBack(ByVal cacheItemArgs As CacheItemArgs) As Object
   9:      Return CBO.FillQueryable(Of Vocabulary)(_DataService.GetVocabularies())
  10:  End Function

In this case the DataService’s GetVocabularies method is called to retrieve a DataReader from the database and pass it to the CBO class to fill an IQueryable collection which is returned by the GetVocabularies method.

We could just write a test similar to the test in Listing 2, which tests that the DataService’s GetVocabularies method is called (and we do in the test project).  However, we also should test that the if the DataReader returns x records then the VocabulryController returns an IQueryable of x Vocabularies.

Listing 4: Testing that the GetVocabularies method returns the correct number of Vocabularies
   1:  [Test]
   2:  public void VocabularyController_GetVocabularies_Returns_List_Of_Vocabularies()
   3:  {
   4:      //Arrange
   5:      Mock<IDataService> mockDataService = new Mock<IDataService>();
   6:      mockDataService.Setup(ds => ds.GetVocabularies())
   7:              .Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount));
   8:      VocabularyController vocabularyController = new VocabularyController(mockDataService.Object);
   9:   
  10:      //Act
  11:      IQueryable<Vocabulary> vocabularys = vocabularyController.GetVocabularies();
  12:   
  13:      //Assert
  14:      Assert.AreEqual<int>(Constants.VOCABULARY_ValidCount, vocabularys.Count());
  15:  }

So just as an in the first test, we create a Mock DataService in line 5.  The major difference is that in lines 6-7 we set up the Mock object to return a valid DataReader.  Moq uses a fluent interface.  The Setup method tells the Mock object which method we are setting up, using our now familiar Lambda expression (ds => ds.GetVocabularies()), and the Returns method tells the Mock object to return the provided object (in this case a valid DataReader with a known count of records).

In line 11, in the “Act” phase we execute the GetVocabularies method to fetch the IQueryable collection, and finally in line 14 we test that the expected number of records was returned.

The main advantage of Mocks is that we only have to implement the method(s) we need to execute the test(s), where as for most other Test Double types we at least have to stub out the implementation.

In future blogs I will show more advanced uses of Moq to enable quite complex tests to be written.


Posted in: Testing  Tags: , , ,

One of the biggest challenges in writing Unit Tests - at least when you write them after you have created the actual code, rather than in a Test Driven Development style, is determining what should be tested.

Lets look at a simple example in TermController.

Figure 1: A simple method which needs Unit Testing
   1:  Public Sub AddTermToContent(ByVal term As Term, ByVal contentItem As ContentItem) _
   2:                  Implements ITermController.AddTermToContent
   3:      'Argument Contract
   4:      Requires.NotNull("term", term)
   5:      Requires.NotNull("contentItem", contentItem)
   6:   
   7:      _DataService.AddTermToContent(term, contentItem)
   8:  End Sub

What do we need to test?

  1. Passing a null Term should throw an exception
  2. Passing a null ContentItem should throw an exception
  3. Passing valid (non-null) arguments should cause the AddTermToContent method of the _DataService to be executed

Are there any more – should we test that adding the term to the content item actually results in the association being made, or should we test what happens if this term is already associated with the content item?

The short answer is No – we don’t need to test these cases as that is the responsibility of the DataService, the Controller’s responsibility is to validate the data passed, possibly execute some business logic, and pass control to the data layer, and this is all covered by these three tests.  We would test these scenarios when writing tests for the DataService itself.

Lets look at a more complex method from the same class.

Figure 2: A more complex method which needs Unit Testing
   1:  Public Function AddTerm(ByVal term As Term) As Integer _
   2:                          Implements ITermController.AddTerm
   3:      'Argument Contract
   4:      Requires.NotNull("term", term)
   5:      Requires.PropertyNotNegative("term", "VocabularyId", term.VocabularyId)
   6:      Requires.PropertyNotNullOrEmpty("term", "Name", term.Name)
   7:   
   8:      If (term.IsHeirarchical) Then
   9:          term.TermId = _DataService.AddHeirarchicalTerm(term, _
  10:                                      UserController.GetCurrentUserInfo.UserID)
  11:      Else
  12:          term.TermId = _DataService.AddSimpleTerm(term, _
  13:                                      UserController.GetCurrentUserInfo.UserID)
  14:      End If
  15:   
  16:      'Clear Cache
  17:      DataCache.RemoveCache(String.Format(_CacheKey, term.VocabularyId))
  18:   
  19:      Return term.TermId
  20:  End Function

In this example we have a much longer list of tests.

  1. Passing a null Term should throw an exception
  2. Passing a Term with a negative VocabularyId should throw an exception
  3. Passing a Term with a null or empty name should throw an exception
  4. If a valid simple Term is passed to the method then the AddSimpleTerm method of _DataService should be called
  5. If a valid simple Term is passed to the method then the TermId property should be set
  6. If a valid simple Term is passed to the method then the TermId should be returned
  7. If a valid hierarchical Term is passed to the method then the AddHeirarchcialTerm method of _DataService should be called
  8. If a valid hierarchical Term is passed to the method then the TermId property should be set
  9. If a valid hierarchical Term is passed to the method then the TermId should be returned
  10. If a valid Term is passed to the method then the Term cache should be cleared.

Both of these examples demonstrate that you need to analyze the method and determine what are its responsibilities when you determine what Unit Tests to write for it.


Posted in: Testing  Tags: , , ,

As many of you will have gathered by reading this blog I am an avid genealogist.  I have been researching my family tree for longer than I have been developing software for a living.  At one time I even considered a career as a Professional Genealogy Researcher.

I have made many attempts to combine my two passions – and recently I launched a new Open Source Project on Codeplex – The Family Tree Project.

This project has a number of goals.

  1. Create an ASP.NET MVC sample application to manage genealogical data.
  2. Create a DotNetNuke Module, using the MVP (Model View Presenter) pattern
  3. Create a common Business and Data Layer that can be used by both the MVC application and the DotNetNuke module
  4. Provide a full set of Unit Tests
  5. Develop a .NET Library for working with GEDCOM files – GEDCOM is a standard file format for the interchange of Genealogical Data

Ultimately the goal for this project is to provide users with the tools to manage their genealogical data online, whether through a standard Web Application (MVC) or through a DotNetNuke site (DNN module).

While all the code is currently available on the Codeplex site, it doesn’t yet do very much – it is basically in a proof of concept stage.  It has 50 tests, which cover about 65% of the code.

Yesterday I upgraded the MVC portion to support the latest preview (Preview 5), and after I return from Open Force Europe next month I hope to be able to flesh the project out and provide a little more functionality.

And I will be blogging about my progress.


 Search Blog

 Adsense

 Calendar

«  September 2010  »
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
View posts in large calendar

 Tags

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 Thoughts from the Wet Coast