应该Mock <someclasstype> .SetupAllProperties()会导致属性返回它们被赋值的值吗?</someclasstype>

时间:2010-09-29 17:20:35

标签: moq stub

当我在Mock上使用SetupAllProperties时,它按预期工作:

/// <summary>
/// demos SetupAllProprties on an interface.  This seems to work fine.
/// </summary>
[Test]
public void Demo_SetupAllProperties_forAnInterface()
{
    var mock = new Mock<IAddress>();

    mock.SetupAllProperties();
    var stub = mock.Object;
    stub.City = "blahsville";

    var retrievedCity = stub.City;
    Assert.AreEqual("blahsville", retrievedCity);
}

但是,当我在课堂上尝试时,它会失败:

/// <summary>
/// demos SetupAllProprties on a class.  This seems to work fine for mocking interfaces, but not classes.  :(  The Get accessor returns null even after setting a property.
/// </summary>
[Test]
public void Demo_SetupAllProperties_forAClass()
{
    var mock = new Mock<Address>();

    mock.SetupAllProperties();
    var stub = mock.Object;
    stub.City = "blahsville";

    var retrievedCity = stub.City;
    Assert.AreEqual("blahsville", retrievedCity);
}

我做错了什么吗?我试图做一些不受moq支持的事情吗?

为了更好地衡量,这里是IAddress接口和Address类:

public interface IAddress
{
    string City { get; set; }
    string State { get; set; }
    void SomeMethod(string arg1, string arg2);
    string GetFormattedAddress();
}

public class Address : IAddress
{
    #region IAddress Members
    public virtual string City { get; set; }
    public virtual string State { get; set; }
    public virtual string GetFormattedAddress()
    {
        return City + ", " + State;
    }

    public virtual void SomeMethod(string arg1, string arg2)
    {
        // blah!
    }
    #endregion
}

1 个答案:

答案 0 :(得分:1)

我将您的代码复制到新项目中无法重现您的问题。我在Demo_SetupAllProperties_forAClass()行的Assert.AreEqual设置了断点,retrievedCity的值为"blahsville"

我正在使用xUnit,但我不认为这会有所作为。您使用的是什么版本的Moq?我使用的是4.0.10510.6。