[英]Register a Moq mock object as type for a Unity container
Since my sut class has a constructor with a IUnityContainer
as parameter I like to setup a new Unity container im my unit test and pass it to the sut. 由于我的sut类有一个带有
IUnityContainer
作为参数的构造函数,我喜欢在我的单元测试中设置一个新的Unity容器并将其传递给sut。 I like to use Moq here because I also have to veryfy for certain method calls. 我喜欢在这里使用Moq,因为我还必须非常适合某些方法调用。 What I've tried here is
我在这里尝试的是
public interface IFoo
{
void Bar();
}
class Program
{
static void Main(string[] args)
{
var fooMock = new Mock<IFoo>();
fooMock.Setup(x => x.Bar()).Callback(() => Console.WriteLine("Hello"));
IUnityContainer container = new UnityContainer();
container.RegisterType(typeof (IFoo), fooMock.Object.GetType());
var sut = container.Resolve<IFoo>();
sut.Bar();
Console.Read();
}
}
But this results in an ResulutionFailedException
. 但这会导致
ResulutionFailedException
。 Any ideas what I can do or what might be an alternative to this problem? 任何想法我能做什么或可能替代这个问题?
您已经有一个对象IFoo fooMock
的实例,因此您需要使用RegisterInstance方法进行注册 :
container.RegisterInstance<IFoo>(fooMock.Object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.