Telerik blogs

In this post , I will show how you can mock  members from MsCorlib. This is more of an introductory post and shows what you need to do in order to successfully mock an MsCorlib member.

If you are planning to mock File or DateTime then the process is pretty straight forward , you just need to put a MockClassAttribute on top your test class. The process for intercepting  such is bit different as we don’t want to get your code through the particular logic for every other type and make your test slower. Therefore, we limit it to an attribute declaration to mark that the test class has some framework members to mock ahead.

In a simple example, let’s say I want to assert a DateTime:

  1.  
  2. [TestMethod]
  3. public void WhenDateTimeNowIsCalledItShouldReturnMockedValue()
  4. {
  5.     Mock.Arrange(() => DateTime.Now).Returns(new DateTime(1900, 2, 1));
  6.  
  7.     var now = DateTime.Now;
  8.  
  9.     Assert.Equal(1900, now.Year);
  10. }

Or Let’s say I want just want to check if File.Delete  is invoked:

  1. [TestMethod]
  2. public void WhenFileIsDeletedItShouldInvokeTheMockedImplementation()
  3. {
  4.     var filename = this.GetType().Assembly.ManifestModule.FullyQualifiedName;
  5.     var fi = new FileInfo(filename);
  6.  
  7.     bool called = false;
  8.  
  9.     Mock.Arrange(() => fi.Delete()).DoInstead(() => called = true);
  10.  
  11.     fi.Delete();
  12.  
  13.     Assert.True(called);
  14. }

These require no special treatment other than the attribute declaration.  But what about other types from MsCorlib and can we mock them ?  Yes we can! We can mock virtually any MsCorlib type using JustMock. The only pre-requisite is to initialize it during the setup. The process is called pre-interception.  It is required in a sense that you don’t have to include test specific attribute in each test method and keep it in one place. Therefore, lets say I want to mock DriveInfo.GetDrives(). All is required that you initialize it during setup in the following way:

  1.  
  2. [ClassInitialize]
  3. public static void Initialize(TestContext context)
  4. {
  5.     Mock.Partial<DriveInfo>().For(() => DriveInfo.GetDrives());
  6. }

 

The rest is plane old vanilla:

  1. [Test]
  2. public void WhenDriveInfoGetDrivesIsCalledItShouldExecuteTheMockedSetup()
  3. {
  4.     bool called = false;
  5.  
  6.     Mock.Arrange(() => DriveInfo.GetDrives()).DoInstead(() => called = true);
  7.  
  8.     DriveInfo.GetDrives();
  9.  
  10.     Assert.True(called);
  11. }

You can further elevate it to initialize all its member:

  1. Mock.Initialize<DriveInfo>();

 

Hope that you find this useful. If you have any questions or ideas please directly contact the JustMock support team.  Finally, this is a JustMock Commercial edition feature thus not available in the free version.

 

Thanks


Comments

Comments are disabled in preview mode.