Mat*_*teo 3 c# unit-testing moq unity-container
下面是我试图进行单元测试的生产代码示例.我正在努力解决对正在使用的具体类的依赖.
public MyClass(IUnityContainer container)
{
this.unityContainer = container;
}
public string DoWork()
{
var sender = unityContainer.Resolve<IInterface>(); // how to setup this object
var json = sender.Send("something");
var value = serializer.Deserialize<SomeModel>(json);
return value.url;
}
Run Code Online (Sandbox Code Playgroud)
我想模仿这种方法使用的IInterface.如何在我的单元测试代码中进行设置?我觉得这里缺少一些东西.这有一种反模式的气味......
这有一种反模式的气味
当然可以.为什么要将实例传递给DI容器到业务对象的构造函数中?你应该通过IInterface代替.请参阅构造函数中的Dependency Injection容器.
Anyway to make this work in your unit test, you just have to set up the container to return an instance or a mock of IInterface. Like this:
public void MyUnitTest()
{
IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<IInterface, YourInstance>();
MyClass classUnderTest = new MyClass(myContainer);
classUnderTest.DoWork();
Assert...
}
Run Code Online (Sandbox Code Playgroud)
See How to use Unity.RegisterType with Moq? to mock the YourInstance.