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

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>()
			Executing.This(() => new AClass(null)).Should().Throw()

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

		public void Example()
			(new Action(() => new SillyClass(null)))

			(new Action(() => new SillyClass(null)))
							.And.ValueOf.InnerExceptions().Select(e => e.GetType())

			(new Action(() => new SillyClass(null)))
									.And.ValueOf.Message.Should().Be.EqualTo("mess null");

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


No comments yet.