Actions Assertions

The assertions over Action is basically to check a possible Exception executing the Action.
			(new Action(() => new AClass(null))).Should().Throw(); // for no specific exception type
			(new Action(() => new AClass(null))).Should().Throw<ArgumentNullException>();
			(new Action(() => new AClass("valid parameter"))).Should().NotThrow();

The .Should().Throw allow chain and the ValueOf come in play again.
			(new Action(() => new AClass(null)))
				.Should().Throw<ArgumentNullException>()
				.And.
				ValueOf.ParamName
					.Should().Be.EqualTo("obj");

To avoid the creation of a new Action Sharp Tests Ex has a static class Executing so you can use even the follow syntax:
			Executing.This(() => new AClass(null)).Should().Throw<ArgumentNullException>()
				.And.ValueOf.ParamName.Should().Be.EqualTo("obj");
or
			Executing.This(() => new AClass(null)).Should().Throw()
				.And.Exception.Should().Be.InstanceOf<ArgumentException>();

The Executing extension

The usage of the static class Executing is particularly useful to test constructors, but when you have an instance of a class, and you need to test a method call, you can use the Executing extension.

For example, given a class like this
		private class MyClass
		{
			public void Method(string value)
			{
				if (value == null)
				{
					throw new ArgumentNullException("value","My message");
				}
			}
		}
you can test the behaviour of the method with:
			var actual = new MyClass();
			actual.Executing(a => a.Method(null)).Throws<ArgumentNullException>();
			actual.Executing(a => a.Method(null)).Throws();
			actual.Executing(a => a.Method("somethig")).NotThrows();

Examples using ExceptionExtensions and LINQ

Sharp Tests Ex offer two additional useful extensions to easy work with the Exception tree.
		public class SillyClass
		{
			public SillyClass(object obj)
			{
				if (obj == null)
				{
					throw new ArgumentException("mess",
							new ArgumentNullException("mess null",
								new ArgumentOutOfRangeException("obj")));
				}
			}
		}

		[TestMethod]
		public void Example()
		{
			(new Action(() => new SillyClass(null)))
							.Should().Throw<ArgumentException>()
							.And.ValueOf.InnerExceptions()
									.OfType<ArgumentOutOfRangeException>().First()
									.ParamName.Should().Be.EqualTo("obj");

			(new Action(() => new SillyClass(null)))
							.Should().Throw<ArgumentException>()
							.And.ValueOf.InnerExceptions().Select(e => e.GetType())
										.Should().Contain(typeof(ArgumentOutOfRangeException));

			(new Action(() => new SillyClass(null)))
							.Should().Throw<ArgumentException>()
							.And.ValueOf.InnerException
									.Should().Be.OfType<ArgumentNullException>()
									.And.ValueOf.Message.Should().Be.EqualTo("mess null");
		}

Last edited Apr 13, 2010 at 10:19 PM by fabiomaulo, version 7

Comments

No comments yet.