如何模拟(有MOQ)统一方法 [英] How to Mock (with Moq) Unity methods
问题描述
扩展方法都没有测试好(这是这里描述的:<一href="http://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq">http://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq, <一href="http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomockextensionmethods.aspx">http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomockextensionmethods.aspx).
Extension methods are not good for testing (that's described here: http://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq, http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomockextensionmethods.aspx).
但可能有一些解决方案,嘲讽的统一方法呢?在我的情况我有以下功能:
But probably there are some solutions for mocking of Unity methods? In my case I have the following function:
public class MyManager
{
public MyManager(IUnityContainer container) : base(container) { }
public IResult DoJob(IData data)
{
IMyLog log = MyContainer.Resolve<IMyLog>();
... use log.Id ...
MyContainer.Resolve<...>();//usage for other purposes...
}
我想,以确保'DoJob的方法总是会得到来自容器IMyLog的对象,而不是从其他渠道......我怎么能测试?
I want to be sure that 'DoJob' method will always get 'IMyLog' object from container, but not from other sources... how could I test that?
我最初的想法是改变DoJob法的实施和使用:
My original idea was to change 'DoJob' method implementation and use:
IMyLog log = UnityContainer.Resolve(typeof(IMyLog)) as IMyLog;
不过,解决(T型,...)也是一个扩展方法...
But 'Resolve(Type t, ...)' is also an extension method...
任何的想法是值得欢迎的。
Any thoughts are welcome.
P.S。请注意,我的日志对象从MyManager.DoJob ...
P.S. Please note, that 'my log' object is created far-away from MyManager.DoJob...
推荐答案
猜,我发现最合适的解决方案测试:这是没有必要的模拟团结容器,并检查日志对象是从它拍摄。我只想做一个模拟的日志的对象,在容器中注册其对象实例和检查测试,如果该日志对象真正使用。
Guess, I found most appropriate solution for test: It is not necessary to mock unity container and check if 'log' object was taken from it. I will just make a mock for 'Log' object, register its object instance in the container and check in test if this log object is really used.
这将做什么是必需的。
Mock<IMyLog> mockLog = new Mock<IMyLog>();
mockLog.Setup(mock=>mock.Id).Returns(TestLogId);
IUnityContainer container = new UnityContainer();
container
.RegisterInstance(mockCommandExecutionLog.Object)
...
;
...
mockLog.Verify(
mock => mock.Id,
Times.Once(),
"It seems like 'Log' object is not used"
);
感谢。
这篇关于如何模拟(有MOQ)统一方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!