Databases Reference
In-Depth Information
Assert.IsTrue(e.ValidationResult.MemberNames.Contains(“UnitPrice”));
}
}
}
Unfortunately, you would also need to ensure that an exception is indeed thrown and
that it is of the expected type. This requires almost a dozen lines of code to do what the
ExpectedExceptionAttribute did in just one and makes automated tests verbose, discour-
aging developers from doing it.
Luckily, the Visual Studio unit-testing framework supports custom assertion attributes,
and you can create one specifically to verify ValidationException instances. Instead
of using the try / catch block, you can replace the ExpectedExceptionAttribute in
the original version of the UnitPrice_IsRequired test method with the custom
ExpectedValidationExceptionAttribute , shown in Listing 8.3, and implement the same
test logic:
[TestMethod]
[ExpectedValidationException(MemberName = “UnitPrice”)]
public void UnitPrice_IsRequired()
LISTING 8.3 ExpectedValidationExceptionAttribute
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DataModel
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ExpectedValidationExceptionAttribute: ExpectedExceptionBaseAttribute
{
public string MemberName { get; set; }
protected override void Verify(Exception exception)
{
this.RethrowIfAssertException(exception);
IEnumerable<string> memberNames = null;
var validationException = exception as ValidationException;
if (validationException != null)
memberNames = validationException.ValidationResult.MemberNames;
Search WWH ::




Custom Search