Search code examples
c#unit-testingvisual-studio-2022mstestmicrosoft-fakes

Microsoft Fakes Shims in .Net 6.0


I m trying to enable shims in my testing via Microsoft Fakes by following this article:

https://learn.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies-for-unit-testing?view=vs-2022&tabs=csharp

However, instead of using .Net Framework 4.8 as mentioned I need to make it work for current .Net versions so I created a project with .NET 6.0.

I created MSTest project and added Fakes assemblies (added for both System and System.IO), and included this code, as per the article above:

public void TestFileReadAllLine()
{
    using (ShimsContext.Create())
    {
        // Arrange
        System.IO.Fakes.ShimFile.ReadAllLinesString = (s) => new string[] { "Hello", "World", "Shims" };
    }
}

The problem is that I simply cannot compile it. The compiler error is:

Error CS0234 The type or namespace name 'Fakes' does not exist in the namespace 'System.IO' (are you missing an assembly reference?).

The article doesn't mention that any additional assembly references needed to be added (besides adding fakes assemblies).

Am I missing something? Did something change in this usage for current .Net versions?


Solution

  • Edit:

    I also tried to build the same project using .NET 5.0 and .NET Core 3.1. In this case I got the compiler error that ShimFile is not found. By trial and error, I found that adding Fakes Assembly to System.IO.FileSystem fixes this (my guess is System.Runtime Fakes Assembly should remain as well).

    So it seems that because the structure of system assemblies changed, it might take some trial and error to get different Fakes APIs to work (unless there are some docs on this that I couldn't find).

    Original answer:

    I found an answer here:

    https://learn.microsoft.com/en-us/answers/questions/1165722/why-i-cant-fake-mock-system-in-net-core-6-0(vs-ent

    Basically, just need to add Fakes Assembly to System.Runtime instead of System or System.IO. After that it works.