TDD相关问题。
我可以查看该属性的年份是List<int>
:
Assert.IsInstanceOf<List<int>>(viewModel.Years);
但是,年份可以是List<int>
或包含List<int>
的对象。
例如
public class ViewModel
{
public List<int> Years {get;set;}
or
public object Years {get;set;}
}
我问这个是因为编码VS时会生成类型为object的Years属性。
一种可能的解决方案是:
Assert.AreEqual(yearsList, (List<int>)viewModel.Years);
当我生成年份时,它将是List<int>
类型。
还有其他方法可以确保年份的类型正确吗?
答案 0 :(得分:2)
绕过您是否应该对此进行测试的问题,至少不要测试Years
是List<int>
,而应该测试它是IList<int>
。第二,你真的需要一些强大的东西吗?你可以逃脱ICollection<int>
或IEnumerable<int>
。你应该测试你需要的最弱的类型。
然后,我会说:
static class ObjectExtensions {
public static bool Implements(this object o, Type type) {
Contract.Requires<ArgumentNullException>(o != null);
Contract.Requires<ArgumentNullException>(type != null);
Contract.Requires<ArgumentException>(type.IsInterface);
return o.GetType()
.GetInterfaces()
.Contains(type);
}
}
用法:
[Test]
public void Years_is_an_object_that_implements_ilist_int() {
// viewModel is ViewModel
Assert.IsNotNull(viewModel.Years);
Assert.AreEqual(true, viewModel.Years.Implements(typeof(IList<int>));
}
答案 1 :(得分:1)
对我来说最好的解决方案是:
Assert.IsTrue(viewModel.Years is List<int>)
但它不起作用:(即使在resharper
只有工作和漂亮的方式是这样的:
Assert.IsNotNull(viewModel.Years as List<int>)
FYI
ReSharper也不够聪明,无法确定正确的类型。
答案 2 :(得分:0)
我从两个答案中都取得了最好的成绩:
我的解决方案
namespace Tests
{
public class AssertExt
{
public static void IsOfType<T>(T entity)
{
}
public static void IsOfType<T>(T entity, string message)
{
}
}
}
我现在可以这样写:
AssertExt.IsOfType<Dictionary<int, string>>(viewModel.PrintFor);
VS将生成正确类型的属性。
不幸的是我无法为NUnit的Assert类创建扩展。
我不知道为什么它不允许我有像
这样的东西Assert.IsOfType<Dictionary<int, string>>(viewModel.PrintFor);
问题可能是Assert的受保护构造函数?