2

I'm unit testing some code that checks the current OS version because a method within a dll will only work on Windows 7. To do this the following is used

if (Environment.OSVersion.Version >= new Version("6.2"))
    //Windows 8
else
    //Windows 7

Is there a simple way to unit test this or will the code need to be changed (wrap and inject Environment?)

LWood
  • 417
  • 4
  • 16
  • There obviously plenty of existing questions on this topic like http://stackoverflow.com/questions/6499871/mock-file-io-static-class-in-c-sharp - please make sure to explain why existing suggestions don't work for you. – Alexei Levenkov Jan 14 '16 at 17:02
  • @AlexeiLevenkov The answer you linked doesn't mention MS Fakes - most answers just say to wrap, which this question is explicitly rejecting. In addition, it's a bit more complex then a normal fake, as you have to edit the `mscorlib.fakes` configuration file, so I think it's worth an answer. Personally, I would wrap the check so that I didn't have to use Fakes, but it's always a powerful tool to know about. – RB. Jan 14 '16 at 17:10
  • @RB. Saying that OP did not search at all is not polite, so I tried to be a bit nicer... Some basic search like https://www.bing.com/search?q=C%23+unittest+static+method brings several SO answers including http://stackoverflow.com/questions/10632975/static-class-method-property-in-unit-test-stop-it-or-not which refers to Moles/Fakes as an option as well as couple injection options... (Actually not even sure what I wanted to say with theses comments... clearly 21 views means not many people care about this post anyway :) ) – Alexei Levenkov Jan 15 '16 at 04:15

1 Answers1

8

You can use Microsoft Fakes (assuming you have, I think, Ultimate edition of Visual Studio).

https://msdn.microsoft.com/en-us/library/hh549175.aspx

This will allow you to fake out static methods :)

Add a Fakes assembly for System: Fakes solution explorer

Open "Fakes → mscorlib.fakes" and edit it to look like this:

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add FullName="System.Environment"/>
  </ShimGeneration>
</Fakes>

Perform a build.

You can now write your unit test:

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        System.Fakes.ShimEnvironment.OSVersionGet = () => new OperatingSystem(PlatformID.Win32Windows, new Version("99.99"));

        Assert.AreEqual(Environment.OSVersion.Version.Major, 99);
    }
}
RB.
  • 36,301
  • 12
  • 91
  • 131