Skip to content

Commit

Permalink
Add Throws for exceptions to the docs (#795)
Browse files Browse the repository at this point in the history
* Add Throws for exceptions to the docs
* Update ExtractDocs.fs to import ExceptionExtensions
  • Loading branch information
304NotModified committed Apr 30, 2024
1 parent 19b38fd commit 1f2fb0f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions build/ExtractDocs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ using System.Collections.Generic;
using System.ComponentModel;
using NSubstitute.Extensions;
using NSubstitute.Compatibility;
using NSubstitute.ExceptionExtensions;
namespace NSubstitute.Samples {
public class Tests_%s {
Expand Down
23 changes: 20 additions & 3 deletions docs/help/_posts/2010-05-02-throwing-exceptions.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Throwing exceptions
layout: post
---

[Callbacks](/help/callbacks) can be used to throw exceptions when a member is called.

<!--
```requiredcode
public interface ICalculator { int Add(int a, int b); }
Expand All @@ -13,6 +11,25 @@ ICalculator calculator;
```
-->

The `Throws` and `ThrowsAsync` helpers in the `NSubstitute.ExceptionExtensions` namespace can be used to throw exceptions when a member is called.

```csharp
//For non-voids:
calculator.Add(-1, -1).Throws(new Exception()); // Or .Throws<Exception>()
//For voids and non-voids:
calculator
.When(x => x.Add(-2, -2))
.Throw(x => new Exception()); // Or .Throw<Exception>() - - don't use .Throw*s* in this case
//Both calls will now throw.
Assert.Throws<Exception>(() => calculator.Add(-1, -1));
Assert.Throws<Exception>(() => calculator.Add(-2, -2));
```

### Returns
Another way is to use the underlying method, `.Returns`. See also [Callbacks](/help/callbacks).

```csharp
//For non-voids:
calculator.Add(-1, -1).Returns(x => { throw new Exception(); });
Expand All @@ -25,4 +42,4 @@ calculator
//Both calls will now throw.
Assert.Throws<Exception>(() => calculator.Add(-1, -1));
Assert.Throws<Exception>(() => calculator.Add(-2, -2));
```
```

0 comments on commit 1f2fb0f

Please sign in to comment.