Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Throws for exceptions to the docs #795

Merged
merged 11 commits into from
Apr 30, 2024
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));
```
```
Loading