Shimming a class instantiated by a static class

别来无恙 提交于 2019-12-12 04:15:03

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/34122823/shimming-a-class-instantiated-by-a-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!