Search code examples
c#asp.net-mvcmbunit

Convert modelstate validation strings to array of objects


Still not comfortable with all the enumerables out there. I'm trying to do this:

 Assert.IsTrue(actionResult.ViewData.ModelState.IsValid, null, Enumerable.ToArray<object>(actionResult.ViewData.ModelState as IEnumerable<object>));

It's an mbUnit assert with the following signature.

public static void IsTrue(bool actualValue, string messageFormat, params object[] messageArgs);

The third parameters causes (translated to english)

System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Coin.UnitTests.AccountControllerTests.MyTest() in D:...\Tests\MbUnitTests\ControllerTests.cs:row 85

in Gallio. How do you do it?

Btw, does anybody know how to get these messages in English? Vista is in Swedish.


Solution

  • ModelState does not implement IEnumerable<T> so the cast ends up being null and Enumerable.ToArray() doesn't like nulls, hence the exception.

    Try something like this:

    var errors = actionResult.ViewData.ModelState.Errors.Select(e => e.ErrorMessage).ToArray();
    Assert.IsTrue(actionResult.ViewData.ModelState.IsValid, string.Join("\n", errors));