继承的 Rhino 模拟 class

Rhino mock of inherited class

我正在尝试模拟没有虚拟方法的 System.Web.Mvc.ModelStateDictionary。所以我试着用这种方式制作一个子class:

public abstract class ModelStateDictionaryMock : ModelStateDictionary
{
    public new abstract int Count { get; }

    public new abstract bool IsReadOnly { get; }

    public new abstract bool IsValid { get; }

    public new abstract ICollection<string> Keys { get; }

    public new abstract ICollection<ModelState> Values { get; }

    public new abstract ModelState this[string key] { get; set; }

    public new abstract void Add(KeyValuePair<string, ModelState> item);

    public new abstract void Add(string key, ModelState value);

    public new abstract void AddModelError(string key, Exception exception);

    public new abstract void AddModelError(string key, string errorMessage);

    public new abstract void Clear();

    public new abstract bool Contains(KeyValuePair<string, ModelState> item);

    public new abstract bool ContainsKey(string key);

    public new abstract void CopyTo(KeyValuePair<string, ModelState>[] array, int arrayIndex);

    public new abstract IEnumerator<KeyValuePair<string, ModelState>> GetEnumerator();

    public new abstract bool IsValidField(string key);

    public new abstract void Merge(ModelStateDictionary dictionary);

    public new abstract bool Remove(KeyValuePair<string, ModelState> item);

    public new abstract bool Remove(string key);

    public new abstract void SetModelValue(string key, ValueProviderResult value);

    public new abstract bool TryGetValue(string key, out ModelState value);
}

然而,当我使用 var modelStateDictionary = MockRepository.GenerateMock<ModelStateDictionaryMock>(); 生成模拟时,我得到一个具有双重属性集的​​对象,如下所示:

执行 modelStateDictionary.Count 访问基础 属性,所以我的模拟不起作用。有谁知道如何解决这个问题?

您获得了双重属性集,因为您在 mock class 中使用 "new" 关键字定义方法。这将方法视为新方法,与基方法无关。

另外,因为基础 class 方法不是抽象的或虚拟的,所以你真的不能覆盖它。

至于解决你的模拟问题,通常不需要模拟 ModelState 字典。一旦你有了控制器引用,你就可以访问它的 ModelState,在那里你可以设置模型错误等使用真实对象,而不是模拟它。

查看此 post 以了解有关如何在模型状态上设置错误的详细信息:How to mock ModelState.IsValid using the Moq framework?

您应该设置您的 mock 以使其具有 return 值。

modelStateDictionary.Stub(x => x.Count).Return(10);

现在,如果您询问 modelStateDictionary.Count,它将 return 10 而不是使用基本实现。