views:

1075

answers:

2

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..

+2  A: 

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; }
}
Darin Dimitrov
When I try that, I get the following exception:Test method ZooCms.Core.Tests.Model.ZooNodeTest.TestSetParentAddsNodeToParentNodeList threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
Chance
Sample code would be helpful here.
Darin Dimitrov
Okay - editing it in
Chance
Ah - figured it out, any object that it uses needs to be virtual.. thanks man
Chance
+1  A: 

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 };
Craig Wilson