如何将模拟对象传递给另一个模拟对象构造函数

时间:2013-02-07 22:35:49

标签: c# unit-testing moq

    /// <summary>
    ///A test for ReverseName
    ///</summary>
    [TestMethod()]
    public void ReverseNameTest()
    {
        Mock<IEntityName> entityName = new Mock<IEntityName>();
        entityName.SetupProperty(x => x.FirstName, "John");
        entityName.SetupProperty(x => x.LastName, "T.");

        var p = new Person(entityName.Object);

        string expected = "Your reverse name is T. John"; 
        string actual;
        actual = p.ReverseName();
        Assert.AreEqual(expected, actual);
    }
}

//人员类

  public Person(IEntityName EntityName)
    {
        this.EntityName = EntityName;
    }

是否可以在TestMehod中模拟Person类,或者我是否必须如上所述创建Person的实例?

1 个答案:

答案 0 :(得分:1)

是的,你可以。犀牛模拟支持,不确定Moq,但我认为你也可以这样做

看看这个帖子。 Passing Moq mock-objects to constructor

Mocking objects with Moq when constructor has parameters