使用服务定位器进行单元测试 Prism?

发布于 2024-11-03 04:47:26 字数 791 浏览 1 评论 0原文

我正在构建 Prism 4 应用程序,并使用 ServiceLocator 来实例化对象。 ServiceLocator 导致了单元测试问题,这让我想知道是否应该回去将 IoC 容器注入到每个需要它的类中。

以下是存储库基类中的问题示例:

protected RepositoryBase(string filePath, Type contextType, string edmName)
{
    m_Logger = ServiceLocator.Current.GetInstance<ILoggerFacade>();

    // Log invocation
    m_Logger.Log("RepositoryBase constructor invoked.", Category.Info, Priority.None);

    // Create object context
    ...

    // Log completion
    m_Logger.Log("RepositoryBase constructor completed.", Category.Info, Priority.None);
}

我正在为存储库创建单元测试,并且发现 ServiceLocator 不起作用,大概是因为 Prism 没有为我的存储库初始化。测试。

ServiceLocator 可以在测试环境中使用吗?我可以放弃它并返回直接注入 IoC 容器吗?由于服务定位器似乎普遍失宠,我不使用它会更好吗?感谢您的帮助。

I am building a Prism 4 app, and I use the ServiceLocator to instantiate objects. The ServiceLocator is causing unit testing problems, and that leads me to wonder whether I should go back to injecting the IoC container into each class that needs it.

Here is an example of the problem from a repository base class:

protected RepositoryBase(string filePath, Type contextType, string edmName)
{
    m_Logger = ServiceLocator.Current.GetInstance<ILoggerFacade>();

    // Log invocation
    m_Logger.Log("RepositoryBase constructor invoked.", Category.Info, Priority.None);

    // Create object context
    ...

    // Log completion
    m_Logger.Log("RepositoryBase constructor completed.", Category.Info, Priority.None);
}

I am creating unit tests for my repository, and I have discovered that the ServiceLocator doesn't work, presumably because Prism isn't initialized for my test.

Can the ServiceLocator be used in a testing context? Sould I drop it and go back to injecting the IoC container directly? Since service locators seem to be falling out of favor generally, would I be better off not using it? Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沙与沫 2024-11-10 04:47:26

您需要创建一个模拟 IServiceLocator,在测试中使用您的模拟提供程序初始化服务定位器。

应该可以做到这一点。

You need to create a mock IServiceLocator, initialize the service locator with your mock provider in your test.

That should do it.

孤蝉 2024-11-10 04:47:26

我能够成功地对 Prism + Silverlight 4 应用程序进行单元测试,并且想不出您不能在单元测试中使用 ServiceLocator 的任何原因。不过,您需要确保 prism 在代码的 [TestInitialize] 部分中正确初始化。

I was able to unit test a Prism + Silverlight 4 application successfully and can't think of any reason why you shouldn't be able to use ServiceLocator from your unit tests. You will need to ensure that prism is initialized correctly in the [TestInitialize] part of your code though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文