gpt4 book ai didi

c# - 使用 TypeMock 模拟 Autofac 的 "Resolve"扩展方法

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:31 27 4
gpt4 key购买 nike

我正在尝试模拟 Autofac 解析,例如

using System;
using Autofac;
using TypeMock.ArrangeActAssert;

class Program
{
static void Main(string[] args)
{
var inst = Isolate.Fake.Instance<IContainer>();
Isolate.Fake.StaticMethods(typeof(ResolutionExtensions), Members.ReturnNulls);
Isolate.WhenCalled(() => inst.Resolve<IRubber>()).WillReturn(new BubbleGum());
Console.Out.WriteLine(inst.Resolve<IRubber>());
}
}

public interface IRubber
{}

public class BubbleGum : IRubber
{}

来自 Moq,TypeMock 的语法和异常让我很困惑。最初在 TestMethod 中运行它后,我不断收到类似“WhenCalled 无法在没有补充行为的情况下运行”的异常。我尝试为每个人和他们的母亲定义行为,但无济于事。

然后我通过测试运行逐步调试,发现 Autofac 触发了一个实际的异常:IRubber 尚未注册。

所以很明显,静态 Resolve 函数没有被伪造,而且我无法让它被伪造,无论我如何连接它。

Isolate.WhenCalled(() => ResolutionExtensions.Resolve<IRubber>(null)).WillReturn(new BubbleGum());

... Autofac 抛出异常,提示 IComponentContext 不能为空。向它提供可能是伪造的 IContainer(或伪造 IComponentContext)让我回到“IRubber 未注册”错误。

最佳答案

这可能是逆流而上的案例之一——创建“真实”容器所需的代码量,注册了适当的依赖项,与 TypeMock 的配置相比更少或相似。我建议沿着这条路走下去。

除了让目标组件完全依赖于 IContainer 之外,您还可以使用像 Func 这样的“关系类型”,Autofac 隐含地支持它们并且表现力更强,而且易于模拟。 http://nblumhardt.com/2010/01/the-relationship-zoo/有关于该方法的更多信息,http://code.google.com/p/autofac/wiki/DelegateFactories 也是如此。 .

关于c# - 使用 TypeMock 模拟 Autofac 的 "Resolve"扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2750172/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com