0

我想在我的测试项目中使用依赖注入。我正在使用 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.
  }
}

看起来绘图对象没有 Unity 创建的 Shape 对象的引用。有什么办法可以做到这一点?

4

1 回答 1

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();
    }    
}
于 2013-07-18T16:28:01.087 回答