【发布时间】:2016-06-06 09:12:50
【问题描述】:
我试图模拟没有虚拟方法的 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>(); 生成模拟时,我得到一个具有双重属性集的对象,如下所示:
做modelStateDictionary.Count 访问基本属性,所以我的模拟不起作用。有谁知道如何解决这个问题?
【问题讨论】:
-
因为属性没有被覆盖。您刚刚使用
new关键字隐藏了它们。 -
如果有机会,可以考虑使用 Microsoft Fakes(如果您有正确的 Visual Studio 版本)。
-
@Complexity 谢谢。它使用 MS Fakes 工作。我在做
System.Web.Mvc.Fakes.ShimModelStateDictionary.AllInstances.AddModelErrorStringString = (dictionary, key, errorMessage) => { Assert.Fail(errorMessage); }; -
Arrgh,这一切都是因为 MS 没有做虚拟或接口。
-
很高兴能帮上忙。
标签: c# asp.net-mvc unit-testing rhino-mocks