开发者

Moq/StructureMap basics

I'm struggling with some very basic/conceptual problem with Moq and StructureMap. Given the following code, the test fails. Why? It seems that my mocked/injected functionality on the Numbers property is just ignored and it continues to call the original functionality.

[TestFixture]
public class MockBasics
{
    [SetUp]
    public void SetUp()
    {
        var m = new Mock<Foo>();
        m.SetupGet(x => x.Numbers).Returns(() => new List<int> {1, 2, 3, 4, 5, 6});
        ObjectFactory.Inject(m.Object);
    }

    [Test]
    public void DoTest()
    {
        var f = new Foo();

        Assert.IsTrue(f.Numbers.Contains(6));
    }

    public class Foo
    {
        private IList<int> _numbers;
        public virtual IList<int> Numbers
        {
            get { return _numbers; }
            set { _numbers = value; }
        }

        public Foo()
        {
            //_numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; // This passes the test
   开发者_如何学编程         _numbers = new List<int> { 1, 2, 3, 4 };
        }
    }

    public class Bar
    {
        public IList<int> GetNumbers()
        {
            var x = ObjectFactory.GetInstance<Foo>();
            return x.Numbers;
        }
    }
}


Your code does not connect the dots. You are injecting a mock of Foo into the ObjectFactory, and then creating an instance of Foo without involving the ObjectFactory.

I think your intent was:

var b = new Bar();
Assert.IsTrue(b.GetNumbers.Contains(6));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜