Author Topic: Can I handle case insensitive string in the mock?  (Read 1902 times)

0 Members and 1 Guest are viewing this topic.

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Can I handle case insensitive string in the mock?
« on: August 09, 2016, 06:35:10 AM »
C# 6.0,
NUnit 3.4.1 (NuGet package),
NUnit3TestAdapter 3.4.1 (NuGet package),
.Net Framework 4.6.1,
JustMock 2016.2.713.2,
Windows 10 x64,
Testable project uses .Net Framework 4.6.1 also.

We will assume that I have some class under test:

Code - C#: [Select]
  1. public class AppManager {
  2.     public string[] GetAppSets() => Registry.LocalMachine
  3.         .OpenSubKey(@"SOFTWARE\Autodesk\AutoCAD", false)
  4.         ?.GetSubKeyNames();
  5. }

Also, I have the test for GetAppSets method:

Code - C#: [Select]
  1. [Test]
  2. public void GetAppSets_Returns_ValidValue() {
  3.  
  4.     const string subkey = @"SOFTWARE\Autodesk\AutoCAD";
  5.     /* The sets of applications which are based on
  6.      * AutoCAD 2009-2017. */
  7.     string[] fakeSets = new[] { "R17.2", "R18.0",
  8.         "R18.1", "R18.2", "R19.0", "R19.1", "R20.0",
  9.         "R20.1","R21.0" };
  10.  
  11.     RegistryKey rk = Mock.Create<RegistryKey>();
  12.  
  13.     Mock.Arrange(() => rk.GetSubKeyNames()).Returns(
  14.         fakeSets);
  15.  
  16.     Mock.Arrange(() => Registry.LocalMachine.OpenSubKey
  17.     (subkey, false)).Returns(rk);
  18.  
  19.     AppManager appMng = new AppManager();
  20.     string[] appSets = appMng.GetAppSets();
  21.  
  22.     Assert.AreEqual(fakeSets, appSets);
  23. }

This test works successfully.

But this test will be failure if GetAppSets method uses "Software\Autodesk\AutoCAD" or "software\autodesk\autocad" string instead of "SOFTWARE\Autodesk\AutoCAD": the appSets variable will be null if string case will be changed (because that registry key doesn't exist on my computer).

So, at this case either tester needs to know the GetAppSets method implementation (the bad variant), or to handle parameter like the case insensitive string.

Is it possible to use the second variant?

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Can I handle case insensitive string in the mock?
« Reply #1 on: August 12, 2016, 05:50:07 AM »
Today I got the answer from Telerik Team:
Quote from: Svetlozar
Hi,

Thank you for the great question!

Quote from: Andrey Bushman
So, at this case I need to handle parameter like the case insensitive string. Is it possible?
Yes, you can get flexible with our matcher using the Arg.Matches mechanism. For more information you can have a look at this blog post - Handling Arguments in JustMock Arrangements, more specifically - the last paragraph - Using Lambdas for Argument Matching.

In your case I guess that would do the job
Code - C#: [Select]
  1. Mock.Arrange(() => Registry.LocalMachine.OpenSubKey(Arg.Matches<string>(s => s.ToLower() == subkey.ToLower()), false)).Returns(rk);
  2.  

Regards,
Svetlozar
Telerik by Progress