Skip to content

Latest commit

 

History

History
161 lines (128 loc) · 5.46 KB

File metadata and controls

161 lines (128 loc) · 5.46 KB

Verify a method that throws an Exception

Given a method that throws an Exception

static void MethodThatThrows() =>
    throw new("The Message");

snippet source | anchor

That exception behavior can be verified using Verify.Throws:

[Fact]
public Task TestMethodThatThrows() =>
    Throws(MethodThatThrows);

snippet source | anchor

Resulting in the following snapshot file:

{
  Type: Exception,
  Message: The Message,
  StackTrace: at ThrowsTests.MethodThatThrows()
}

snippet source | anchor

IgnoreStackTrace

Often the exception stack trace can be noisy and fragile to causing false failed tests. To exclude it use IgnoreStackTrace:

Fluent API

[Fact]
public Task TestMethodThatThrowsIgnoreStackTraceFluent() =>
    Throws(MethodThatThrows)
        .IgnoreStackTrace();

snippet source | anchor

Settings api

[Fact]
public Task TestMethodThatThrowsIgnoreStackTraceSettings()
{
    var settings = new VerifySettings();
    settings.IgnoreStackTrace();
    return Throws(MethodThatThrows, settings);
}

snippet source | anchor

Globally

VerifierSettings.IgnoreStackTrace();

snippet source | anchor

Result

{
  Type: Exception,
  Message: The Message
}

snippet source | anchor

Async

There are specific named Throws* method for methods that return a Task or a ValueTask.

Task

static async Task MethodThatThrowsTask()
{
    await Task.Delay(1);
    throw new("The Message");
}

snippet source | anchor

[Fact]
public Task TestMethodThatThrowsTask() =>
    ThrowsTask(MethodThatThrowsTask);

snippet source | anchor

ValueTask

static async ValueTask MethodThatThrowsValueTask()
{
    await Task.Delay(1);
    throw new("The Message");
}

snippet source | anchor

[Fact]
public Task TestMethodThatThrowsValueTask() =>
    ThrowsValueTask(MethodThatThrowsValueTask);

snippet source | anchor