1

我正在尝试为访问我的数据层以获取字符串的 HtmlHelper 创建一个单元测试。我看过很多关于这个的帖子,我可能遗漏了一些东西。我遇到的问题是如何模拟对数据层的访问?我通常通过构造函数进行依赖注入,但我不能在这里,因为 html 帮助程序需要是静态的。所以我已经通过一个属性设置了注入,但是我如何从我的单元测试中访问它。对不起,如果这很明显,但它现在把我搞砸了。

这是我所拥有的 -

public static class StringResourceHelper
{

    #region Private Members

    private static IStringResourceService _service;

    #endregion

    #region Public Properties

    private static IStringResourceService Service
    {
        get
        {
            if(_service==null)
            {
                _service = (IStringResourceService)Bootstrapper.Container.Resolve(typeof(IStringResourceService));
            }

            return _service;
        }
    }

    #endregion

    #region Public Methods

    public static string StringResource(this HtmlHelper helper, string label)
    {
        int languageCode;

        if(helper.ViewData["LanguageCode"] == null || !Int32.TryParse(helper.ViewData["LanguageCode"].ToString(), out languageCode))
        {
            languageCode = Constants.LanguageCodes.English;
        }

        return Service.GetString(label, languageCode);
    }

    #endregion

}

如何模拟 Service.GetString 调用?

4

2 回答 2

1

免责声明我在 Typemock 工作

如果您需要模拟/伪造静态方法并且不更改代码,则需要使用Isolator。伪造该方法是使用以下方法完成的:

Isolate.WhenCalled(() => Service.GetString(string.empty, 0)).WillReturn(/*insert return value here*/);

如果要检查传递给 Service.GetString 的参数,请使用以下命令:

Isolate.Verify.WasCalledWithExactArguments(() => Service.GetString(/* use expected arguments*/);
于 2009-11-06T13:26:30.590 回答
0

To start with I would be weary of any static methods that require a member variable. To me that is a sign that you have a object (likely Singletonly scoped). So my first suggestion would be to promote StringResourceHelper to a none-static class and use DI as normal.

If you can't then does your DI framework of choice support static setter injection? Warning bells go off for me if I see something outside the bootstrap playing with the DI framework as it looks to me as if it is you are using the DI framework as a service locator.

If you can't change the class to be none-static and your DI framework does not support static setter injection then I would either:

Set the DI framework up as part of the tests set up to return mocks or add a setter to StringResourceHelper so it can be controlled.

于 2009-10-29T15:53:24.023 回答