0

I have a static class which creates a database class instance. I am looking for a way to shim/stub that database class in my tests.

public partial class Y : Form
{
    static Models.DBModel db = new Models.DBModel();
    ....

Unfortunately I cannot change the code. Is there any way I can mock this database class in my tests?

mimo
  • 6,221
  • 7
  • 42
  • 50
rev
  • 1
  • 1
  • If the call to this variable goes through one method then you could override this method. Othervise, you could try to use some special frameworks like [TypeMock](http://www.typemock.com/) or [Fakes](https://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx) – Sergii Zhevzhyk Dec 07 '15 at 01:18
  • I am using Fakes! Sorry, someone removed this information from the topic title. I was asking for a way to do it through fakes. I tried creating a DB shim before instantiating the static class, but the DB instance created by the static class doesn't use the shim. – rev Dec 07 '15 at 08:59
  • Oh, I didn't see - information about Microsoft Fakes was moved to the tag. Is it a private field? Can you change it to protected and then you can override this class and initialize this field in the construnctor. – Sergii Zhevzhyk Dec 07 '15 at 09:06

1 Answers1

0

This worked for me:

I. Update yourdll.fakes to include:

...
<ShimGeneration>
    <Clear/>
    ...
    <Add FullName="Models.DBModel"/>
    ...
</ShimGeneration>
...

II. In your TestClass create method with [TestInitialize] and [TestCleanup] attribute:

using Models.Fakes;

IDisposable shimsContext;

[TestInitialize]
public void SetUp()
{
    shimsContext = ShimsContext.Create();
    ShimDBModel.Constructor = (@this) =>
    {
        ShimDBModel shim = new ShimDBModel(@this)
        {
            // here you can provide shim methods for DBModel
        };
    };
}

[TestCleanup]
public void CleanUp()
{
    // Let's do not forget to clean up shims after each test runs
    shimsContext.Dispose();
}

III. And finally in your test, the Y.db should be Shim created in SetUp method.

[TestMethod]
public void Test()
{
    Y.db... // db should be shim
}
mimo
  • 6,221
  • 7
  • 42
  • 50
  • Can someone provide an example of how to write "// here you can provide shim methods for DBModel" – Migio B Jul 06 '22 at 10:40