开发者

NUnit check that property is a collection

TDD related question.

I can check that property Years is List<int>:

Assert.IsInstanceOf<List<int>>(viewModel.Years);

But Years can be List<int> or object that contains List<int>.

For example

public class ViewModel
{
   public List<int> Years {get;set;}
   or 
   public开发者_运维问答 object Years {get;set;}
}

I'm asking this because while coding VS generates Years property of type object.

One possible solution can be:

Assert.AreEqual(yearsList, (List<int>)viewModel.Years);

When I will generate Years, it will be of List<int> type.

Are there another ways to ensure that Years is of correct type?


Bypassing the question of whether or not you should even be testing this, at a minimum, instead of testing that Years is a List<int> you should be testing that it is an IList<int>. Second, do you really need something that strong? Can you get away with ICollection<int> or IEnumerable<int>. You should be testing the weakest type that you need.

Then, I would say:

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);
    }
}

Usage:

[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>));
}


The best solution for me is this:

Assert.IsTrue(viewModel.Years is List<int>)

but it doesn't work:( even in resharper

only working and nice looking way is this:

Assert.IsNotNull(viewModel.Years as List<int>)

FYI
ReSharper also is not smart enough to determine right type.


I took the best from both answers:

My solution

namespace Tests
{
    public class AssertExt
    {
        public static void IsOfType<T>(T entity) 
        {
        }


        public static void IsOfType<T>(T entity, string message) 
        {
        }
    }
}

I can now write something like this:

AssertExt.IsOfType<Dictionary<int, string>>(viewModel.PrintFor);

And VS will generate property of correct type.

Unfortunately I can't create an extension for NUnit's Assert class.

I don't know why it doesn't allow me to have something like

Assert.IsOfType<Dictionary<int, string>>(viewModel.PrintFor);

Maybe the problem is the Assert's protected constructor?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜