我想在我的测试项目中使用依赖注入。我使用Unity Container 3.0版来实现这一目标。我面临的问题是对象没有被创建。下面是示例代码(虚拟代码) -
注册码 -
var container = new UnityContainer();
container.RegisterType<IShape, Circle>();
container.Resolve<Circle>();
测试类代码 -
[TestClass]
public class UnitTest
{
private Drawing drawing = new Drawing();
[TestMethod]
public void Test1()
{
this.drawing.Draw();
}
}
班级绘图代码 -
public class Drawing
{
private IShape shape;
[Dependency]
public IShape Shape
{
get { return this.shape; }
set { this.shape = value; }
}
public void Draw()
{
this.shape.Draw(); // Error - object reference not set to instance of any object.
}
}
看起来,Drawing对象没有Unity创建的Shape对象的引用。有什么方法可以实现这个目标吗?
答案 0 :(得分:1)
我会使用TestInitialize
属性来创建和配置用于特定测试的容器:
[TestClass]
public class UnitTest
{
private IUnityContainer container;
[TestInitialize]
public void TestInitialize()
{
container = new UnityContainer();
container.RegisterType<IShape, Circle>();
}
[TestMethod]
public void Test1()
{
var drawing = container.Resolve<Drawing>();
// Or Buildup works too:
//
// var drawing = new Drawing();
// container.BuildUp(drawing)
this.drawing.Draw();
}
}