Skip to content

Commit cd93b00

Browse files
authored
Add Catch.OnlyAsync (#529)
1 parent 1981464 commit cd93b00

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/Machine.Specifications.Specs/CatchSpecs.cs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,57 @@ public class with_a_non_throwing_Action
130130
}
131131
}
132132

133+
[Subject(typeof(Catch))]
134+
public class when_calling_Catch_OnlyAsync_with_an_Async_Func
135+
{
136+
[Subject(typeof(Catch))]
137+
public class with_a_throwing_Action_which_matches_exception_to_be_caught
138+
{
139+
static ArgumentException AnException;
140+
static Exception Result;
141+
static Task TestAsync() => Task.Run(() => throw AnException);
142+
143+
Establish context = () => { AnException = new ArgumentException(); };
144+
145+
Because of = async () => { Result = await Catch.OnlyAsync<ArgumentException>(TestAsync); };
146+
147+
It should_return_the_same_exception =
148+
() => Result.Should().BeSameAs(AnException);
149+
}
150+
151+
[Subject(typeof(Catch))]
152+
public class with_a_throwing_Action_which_doesnt_match_exception_to_be_caught
153+
{
154+
static ArgumentException AnException;
155+
static Exception Result;
156+
static Task TestAsync() => Task.Run(() => throw AnException);
157+
158+
Establish context = () => { AnException = new ArgumentException(); };
159+
160+
Because of = async () => { Result = await Catch.ExceptionAsync(async () => await Catch.OnlyAsync<InvalidOperationException>(TestAsync)); };
161+
162+
It should_return_the_same_exception =
163+
() => Result.Should().BeSameAs(AnException);
164+
}
165+
166+
[Subject(typeof(Catch))]
167+
public class with_a_non_throwing_Action
168+
{
169+
static string ActionSideEffect;
170+
static Exception Result;
171+
172+
static Task TestAsync() => Task.Run(() => { ActionSideEffect = "hi"; });
173+
174+
Because of = async () => { Result = await Catch.OnlyAsync<ArgumentException>(TestAsync); };
175+
176+
It should_access_the_propety =
177+
() => ActionSideEffect.Should().Be("hi");
178+
179+
It should_return_null =
180+
() => Result.Should().BeNull();
181+
}
182+
}
183+
133184
[Subject(typeof(Catch))]
134185
public class when_calling_catch_with_async_methods
135186
{

src/Machine.Specifications/Catch.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,5 +78,21 @@ public static TException Only<TException>(Action throwingAction)
7878

7979
return null;
8080
}
81+
82+
#if !NET35 && !NET40
83+
public static async Task<TException> OnlyAsync<TException>(Func<Task> throwingFunc) where TException : Exception
84+
{
85+
try
86+
{
87+
await throwingFunc();
88+
}
89+
catch (TException ex)
90+
{
91+
return ex;
92+
}
93+
94+
return null;
95+
}
96+
#endif
8197
}
8298
}

0 commit comments

Comments
 (0)