Thoughts from the Wet Coast

The musings of an ASP.NET Developer from Canada's We(s)t Coast

DNN Development Tips:7 - Using Moq

Last Modified: May 2 2017
Oct 20 2014

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 pre-programmed with expectations which form a specification of the calls they are expected to receive.

In 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 Taxonomy features.

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 void DeleteVocabulary(Vocabulary vocabulary)
   2:  {
   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:  }

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 lambda expressions a lot, 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 IQueryable GetVocabularies()
   2:  {
   3:      return CBO.GetCachedObject>(new CacheItemArgs(_CacheKey, CacheTimeOut), GetVocabulariesCallBack).AsQueryable();
   4:  }
   5:   
   6:  private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs)
   7:  {
   8:     return CBO.FillQueryable(_DataService.GetVocabularies()).ToList();
   9:  }

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

Disclaimer

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

Categories

Tags