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.