Skip to content

Commit

Permalink
Catch.Only with throwingAction, closes #205
Browse files Browse the repository at this point in the history
  • Loading branch information
danielmarbach committed Jan 23, 2014
1 parent 1ad146c commit c2e17a3
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 4 deletions.
47 changes: 47 additions & 0 deletions Source/Machine.Specifications.Specs/CatchSpecs.cs
Expand Up @@ -81,4 +81,51 @@ public class with_a_non_throwing_Func
() => Result.Should().BeNull();
}
}

[Subject(typeof(Catch))]
public class when_calling_Catch_Only_with_an_Action
{
[Subject(typeof(Catch))]
public class with_a_throwing_Action_which_matches_exception_to_be_caught
{
static ArgumentException AnException;
static Exception Result;

Establish context = () => { AnException = new ArgumentException(); };

Because of = () => { Result = Catch.Only<ArgumentException>(() => { throw AnException; }); };

It should_return_the_same_exception =
() => Result.Should().BeSameAs(AnException);
}

[Subject(typeof(Catch))]
public class with_a_throwing_Action_which_doesnt_match_exception_to_be_caught
{
static ArgumentException AnException;
static Exception Result;

Establish context = () => { AnException = new ArgumentException(); };

Because of = () => { Result = Catch.Exception(() => Catch.Only<InvalidOperationException>(() => { throw AnException; })); };

It should_return_the_same_exception =
() => Result.Should().BeSameAs(AnException);
}

[Subject(typeof(Catch))]
public class with_a_non_throwing_Action
{
static string ActionSideEffect;
static Exception Result;

Because of = () => { Result = Catch.Only<ArgumentException>((() => { ActionSideEffect = "hi"; })); };

It should_access_the_propety =
() => ActionSideEffect.Should().Be("hi");

It should_return_null =
() => Result.Should().BeNull();
}
}
}
14 changes: 10 additions & 4 deletions Source/Machine.Specifications/Catch.cs
Expand Up @@ -5,10 +5,15 @@ namespace Machine.Specifications
public static class Catch
{
public static Exception Exception(Action throwingAction)
{
return Only<Exception>(throwingAction);
}

public static Exception Exception<T>(Func<T> throwingFunc)
{
try
{
throwingAction();
throwingFunc();
}
catch (Exception exception)
{
Expand All @@ -18,13 +23,14 @@ public static Exception Exception(Action throwingAction)
return null;
}

public static Exception Exception<T>(Func<T> throwingFunc)
public static TException Only<TException>(Action throwingAction)
where TException : Exception
{
try
{
throwingFunc();
throwingAction();
}
catch (Exception exception)
catch (TException exception)
{
return exception;
}
Expand Down

0 comments on commit c2e17a3

Please sign in to comment.