Chance
Chance

Reputation: 11323

Having issues with moq

I am trying out moq and I'm running into a problem with the following test body:

var child = new Mock<ZooNode>();
var parent = new Mock<ZooNode>();
child.Object.Parent = parent.Object;
parent.Expect(p => p.Children.Contains(child.Object)).Returns(true);

which throws :

System.ArgumentException: Invalid expectation on a non-overridable member: p => p.Children.Contains(value(ZooCms.Core.Tests.Model.ZooNodeTest+<>c__DisplayClass0).child.Object).

and I'm not quite sure if its moq, but the code that I'm testing is fairly simple. I'm not sure if it matters, but ZooNode is an abstract class.

Thanks in advance.

EDIT

Heres the code after suggested revision from darin's response:

public abstract class ZooNode : ZooObject
{
    private ZooNode _parent{ get; set;}
    public ZooNode Parent { 
        get
        {
            return _parent;
        }
        set
        {
            if(Parent != null) 
                Parent.Children.Remove(value);
            _parent = value;
            _parent.Children.Add(this);
        }
    }
    public virtual IList<ZooNode> Children { get; private set; }

}

it now throws

Test method ZooCms.Core.Tests.Model.ZooNodeTest.TestSetParentAddsNodeToParentNodeList threw exception: System.NullReferenceException: Object reference not set to an instance of an object..

Upvotes: 2

Views: 3881

Answers (2)

Craig Wilson
Craig Wilson

Reputation: 12624

Chance, You are never actually initializing the Children collection. So, either you need to initialize it in a constructor, or you can tell Moq to Mock it by default.

var parent = new Mock<ZooNode>() { DefaultValue = DefaultValue.Mock };

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

Your Children collection property needs to be virtual if you want to define expectations on it:

public abstract class ZooNode
{
    public ZooNode Parent { get; set; }
    public virtual IList<ZooNode> Children { get; set; }
}

Upvotes: 5

Related Questions