0

I have a class like as below:

public class NodeOperator
{
    private NodeInfo _nodeInfo;
    public NodeOperator(NodeInfo nodeInfo)
    {
        _nodeInfo = nodeInfo;
    }
    public bool DoSomething(int dstRackId, int srcRackId, ModuleBase srcModulebase)
    {
        if (dstRackId == srcRackId)
        {
              if (srcModulebase.FieldBus.HardwareConfiguration.DdfInfo.UserDefine.InstallRestrictions.Position == ModulePosition.Right)
                    return true;
              else
                    return false;
        }
        else
            return _nodeInfo.CanAppendModule(dstRackId, srcModulebase, AppendDirection.Right);
    }
}

I want to do the unit test for the DoSomething method, so I write some code as below:

        public void DoSomethingTest()
        {
            var nodeInfo = A.Fake<NodeInfo>();
            var srcModulebase = A.Fake<ModuleBase>();
            A.CallTo(() => srcModulebase.FieldBus.HardwareConfiguration.DdfInfo.UserDefine.InstallRestrictions.Position).Returns(ModulePosition.Right); // throw System.Reflection.TargetException: 
            var nodeOperator = new NodeOperator(nodeInfo);
            int dstRackId = 0;
            int srcRackId = 0;
            Assert.AreEqual(true, nodeOperator.DoSomething(dstRackId, srcRackId, srcModulebase));
            A.CallTo(() => nodeInfo.CanAppendModule(dstRackId, srcModulebase, AppendDirection.Right)).MustNotHaveHappened();
        }

In this function(DoSomething), I don't care if the moduleBase instance is correct or not. Also, I don't care if the properties inside the moduleBase have initialized or not.

So I write the below code to fake the property,

A.CallTo(() => srcModulebase.FieldBus.HardwareConfiguration.DdfInfo.UserDefine.InstallRestrictions.Position).Returns(ModulePosition.Right);

But this cause a Reflection.TargetException:'Non-static methods require targets'. The FieldBus property for srcModulebase is null.

How can I just ignore the initialize inside the fake class and just fake the nested property which I want?

I know in this case, I can just pass the ModulePosition instead of ModuleBase, but I just want to know how to fake a nested property like this case.

Harris.Dai
  • 21
  • 3

1 Answers1

2

I found the solution.

I need to change all the nested properties inside ModuleBase class to Interface or mark all of them to be virtual.

Then I can fake it.

As the documentation says in What members can be overridden:

Once a fake has been constructed, its methods and properties can be overridden if they are:

  • virtual,
  • abstract, or
  • an interface method when an interface is being faked
Community
  • 1
  • 1
Harris.Dai
  • 21
  • 3