C#、Moq、单元测试:如何创建从另一个类继承的对象?

问题描述 投票:0回答:1

我的类/接口设置如下:

Room.cs

//import statements

namespace namespace1
{
   internal class Room: Apartment
   {
      // constructor
      public Room(Furniture furniture) : base(furniture)
      {
      }
   }
}

公寓.cs

// import statements

namespace namespace2
{
   public abstract class Apartment: Building
   {
      private int numChairs = 0;

      // constructor
      protected Apartment(IFurniture furniture) : base(IFurniture furniture)
      {
         this.numChairs = furniture.chairs.Length;
      }
   }
}

建筑.cs

// import statements

namespace namespace3
{
   public abstract class Building
   {
      // constructor
      protected Building(IFurniture furniture)
      {
      }
   }
}

我想创建一个 Room 对象,并带有一个模拟的 Furniture 对象。这是我所做的:

[Test]
public void fun()
{
   var mockedFurniture = new Mock<IFurniture>();
   var room = new Room(mockedFurniture.Object);
}   

问题:因为

Room
的构造函数调用
base(furniture)
,所以
Apartment
的构造函数尝试访问
furniture.chairs
,即
null
。我怎么能嘲笑这个呢?

编辑

问题出在

Apartment.cs
。它尝试访问 Furniture.chairs,即
null
。这是 IFurniture.cs:

public interface IFurniture
{
   IChairs Chairs { get; }
}
c# unit-testing dependency-injection mocking moq
1个回答
0
投票

根据你的例子,你也需要模拟

IChairs

var mockedChairs = new Mock<IChairs>();
var mockedFurniture = new Mock<IFurniture>();
mockedFurniture.Setup(q=>q.Chairs).Returns(mockedChairs.Object);
var room = new Room(mockedFurniture.Object);
© www.soinside.com 2019 - 2024. All rights reserved.