0

I want to mock the hidden property Identity, but MyChannelMock.Object.Identity is null after constructor is called.

The class looks like this:

public abstract class CommunicationRouter<TChannelType>
where TChannelType : class, ICommunicationChannel
{ 
  protected readonly Mock<TChannelType> MyChannelMock;
  protected CommunicationRouter()
  {
        MyChannelMock = new Mock<TChannelType>();
        // object that's not null
        var identity = new SomeIdentity();
        // 1st method I've tried to mock but return is null
        MyChannelMock.Setup(_ => _.Identity).Returns(identity);
        // 2nd method I've tried to mock but return is also null
        MyChannelMock.As<ICommunicationChannel>().Setup(_ => _.Identity).Returns(identity);
  }
 }

interface ICommunicationChannel
{
    public MyType Identity{get;set;}
}

interface ICustomChannel : ICommunicationChannel
{
    public new MyType2 Identity{get;set;}
}

I can not find the problem of this mock nowhere, so I'll appreciate if u can give me any others tips.

Cristi
  • 1
  • 2
  • In addition to the hint of @HimBromBeere you could also try to use `MyChannelMock.SetupGet` to mock the property instead of `MyChannelMock.Setup`. – Markus Feb 21 '22 at 13:14
  • anyway we don't see where you actualy *use* the above object. It would be really helpful to see that code as well. – MakePeaceGreatAgain Feb 21 '22 at 13:23
  • I've used MyChannelMock.SetupGet, same issues. Also the code above is extracted from a bigger context. This is the essential part of it that doesn't work. @HimBromBeere My bad, in the second interface, the Type of Identity is different than in the 1st one. That's why I am using "new". – Cristi Feb 21 '22 at 14:07
  • `new` assumes that the **reference** of the object is of type `ICustomChannel`, not of type `ICommunicationChannel`. So unless you don't provide where you call that property `Identity`, I'd guess it's something lime `ICommunicationChannel channel = ...; var identity = channel.Identity`, whereas you need a reference of type `ICustomChannel`. – MakePeaceGreatAgain Feb 21 '22 at 14:30

0 Answers0