填充由静态类实例化的类 [英] Shimming a class instantiated by a static class

查看:26
本文介绍了填充由静态类实例化的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态类,它创建了一个数据库类实例.我正在寻找一种在我的测试中填充/存根该数据库类的方法.

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?

推荐答案

这对我有用:

我.更新 yourdll.fakes 以包含:

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

二.在您的 TestClass 中使用 [TestInitialize][TestCleanup] 属性创建方法:

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();
}

三.最后在您的测试中,Y.db 应该是在 SetUp 方法中创建的 Shim.

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
}

这篇关于填充由静态类实例化的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆