Search code examples
c#unit-testingdependency-injectionmockingmoq

C#, Moq, Unit-Testing: How to create an object that inherits from another class?


My classes/interfaces are set up like this:

Room.cs

//import statements

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

Apartment.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;
      }
   }
}

Building.cs

// import statements

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

I want to create a Room object, with a mocked Furniture object. Here is what I have done:

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

The issue: because the constructor for Room calls base(furniture), the constructor for Apartment is trying to access furniture.chairs, which is null. How can I mock this?

EDIT

The issue lies in Apartment.cs. It tries to access furniture.chairs, which is null. Here is IFurniture.cs:

public interface IFurniture
{
   IChairs Chairs { get; }
}

Solution

  • According to your example, you need to mock IChairs too.

    var mockedChairs = new Mock<IChairs>();
    var mockedFurniture = new Mock<IFurniture>();
    mockedFurniture.Setup(q=>q.Chairs).Returns(mockedChairs.Object);
    var room = new Room(mockedFurniture.Object);