2

当我在 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);
}

我做错什么了吗?我是否正在尝试做起订量不支持的事情?

为了更好地衡量,这里是 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
}
4

1 回答 1

1

我将您的代码复制到一个新项目中无法重现您的问题。Demo_SetupAllProperties_forAClass()我在该Assert.AreEqual行设置了一个断点并且retrievedCity确实具有该值"blahsville"

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

于 2010-09-29T19:08:09.193 回答