Products

Solutions

Resources

Partners

Community

About

New Community Website

Ordinarily, you'd be at the right spot, but we've recently launched a brand new community website... For the community, by the community.

Yay... Take Me to the Community!

The Community Blog is a personal opinion of community members and by no means the official standpoint of DNN Corp or DNN Platform. This is a place to express personal thoughts about DNNPlatform, the community and its ecosystem. Do you have useful information that you would like to share with the DNN Community in a featured article or blog? If so, please contact .

The use of the Community Blog is covered by our Community Blog Guidelines - please read before commenting or posting.


Adventures in Testing - 5 - Using Moq

This article is cross-posted from my personal blog.

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 mockDataService = new Mock();
   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 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 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 mockDataService = new Mock();
   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 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.

Comments

There are currently no comments, be the first to post one.

Comment Form

Only registered users may post comments.

NewsArchives


Aderson Oliveira (22)
Alec Whittington (11)
Alessandra Daniels (3)
Alex Shirley (10)
Andrew Hoefling (3)
Andrew Nurse (30)
Andy Tryba (1)
Anthony Glenwright (5)
Antonio Chagoury (28)
Ash Prasad (37)
Ben Schmidt (1)
Benjamin Hermann (25)
Benoit Sarton (9)
Beth Firebaugh (12)
Bill Walker (36)
Bob Kruger (5)
Bogdan Litescu (1)
Brian Dukes (2)
Brice Snow (1)
Bruce Chapman (20)
Bryan Andrews (1)
cathal connolly (55)
Charles Nurse (163)
Chris Hammond (213)
Chris Paterra (55)
Clint Patterson (108)
Cuong Dang (21)
Daniel Bartholomew (2)
Daniel Mettler (181)
Daniel Valadas (48)
Dave Buckner (2)
David Poindexter (12)
David Rodriguez (3)
Dennis Shiao (1)
Doug Howell (11)
Erik van Ballegoij (30)
Ernst Peter Tamminga (80)
Francisco Perez Andres (17)
Geoff Barlow (12)
George Alatrash (12)
Gifford Watkins (3)
Gilles Le Pigocher (3)
Ian Robinson (7)
Israel Martinez (17)
Jan Blomquist (2)
Jan Jonas (3)
Jaspreet Bhatia (1)
Jenni Merrifield (6)
Joe Brinkman (274)
John Mitchell (1)
Jon Henning (14)
Jonathan Sheely (4)
Jordan Coopersmith (1)
Joseph Craig (2)
Kan Ma (1)
Keivan Beigi (3)
Kelly Ford (4)
Ken Grierson (10)
Kevin Schreiner (6)
Leigh Pointer (31)
Lorraine Young (60)
Malik Khan (1)
Matt Rutledge (2)
Matthias Schlomann (16)
Mauricio Márquez (5)
Michael Doxsey (7)
Michael Tobisch (3)
Michael Washington (202)
Miguel Gatmaytan (3)
Mike Horton (19)
Mitchel Sellers (40)
Nathan Rover (3)
Navin V Nagiah (14)
Néstor Sánchez (31)
Nik Kalyani (14)
Oliver Hine (1)
Patricio F. Salinas (1)
Patrick Ryan (1)
Peter Donker (54)
Philip Beadle (135)
Philipp Becker (4)
Richard Dumas (22)
Robert J Collins (5)
Roger Selwyn (8)
Ruben Lopez (1)
Ryan Martinez (1)
Sacha Trauwaen (1)
Salar Golestanian (4)
Sanjay Mehrotra (9)
Scott McCulloch (1)
Scott Schlesier (11)
Scott Wilkinson (3)
Scott Willhite (97)
Sebastian Leupold (80)
Shaun Walker (237)
Shawn Mehaffie (17)
Stefan Cullmann (12)
Stefan Kamphuis (12)
Steve Fabian (31)
Steven Fisher (1)
Tony Henrich (3)
Torsten Weggen (3)
Tycho de Waard (4)
Vicenç Masanas (27)
Vincent Nguyen (3)
Vitaly Kozadayev (6)
Will Morgenweck (40)
Will Strohl (180)
William Severance (5)
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out