继承类的犀牛模拟

时间:2016-02-24 07:41:38

标签: c# asp.net-mvc unit-testing rhino-mocks

我试图模拟没有虚方法的System.Web.Mvc.ModelStateDictionary。所以我试图以这种方式创建一个子类:

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>();生成模拟时,我得到一个具有双重属性的对象,如下所示:

Watch 1

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

2 个答案:

答案 0 :(得分:0)

你得到了一组双重属性,因为你在mock类中定义了使用&#34; new&#34;关键词。这将方法视为一种新方法,与基本方法无关。

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

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

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

答案 1 :(得分:0)

您应该设置模拟以使其返回值。

  

modelStateDictionary.Stub(x =&gt; x.Count).Return(10);

现在,如果你问modelStateDictionary.Count它将返回10而不是使用基本实现。