Skip to content

Throwing Exceptions

Arrange methods to throw exceptions instead of returning values. This is useful for testing exception paths and retry logic.

Target type used in examples:

Example

using Imposter.Abstractions;

[assembly: GenerateImposter(typeof(Imposter.Tests.Docs.Methods.IThrowService))]

public interface IThrowService
{
    int GetNumber();
    System.Threading.Tasks.Task<int> GetNumberAsync();
}

Ways to throw

  • Generic type:

Example

imposter.GetNumber().Throws<InvalidOperationException>();

service.GetNumber(); // throws InvalidOperationException
  • Specific instance:

Example

imposter.GetNumber().Throws(new Exception("boom"));

service.GetNumber(); // throws Exception("boom")
  • Factory delegate:

Example

imposter.GetNumber().Throws(() => new Exception("deferred"));

service.GetNumber(); // throws Exception("deferred")

Sequencing with returns

Mix Throws with Returns using Then():

Example

imposter.GetNumber()
    .Returns(1)
    .Then().Throws<InvalidOperationException>()
    .Then().Returns(2);

service.GetNumber(); // 1
service.GetNumber(); // throws InvalidOperationException
service.GetNumber(); // 2

Async methods

For Task/Task or ValueTask/ValueTask, Throws raises the exception when the method is invoked, just like synchronous methods. Use async-aware assertions in tests when appropriate.

Example

imposter.GetNumberAsync().Throws<TimeoutException>();
await Assert.ThrowsAsync<TimeoutException>(() => service.GetNumberAsync());

See more examples on GitHub.

Note

  • Repeating Throws without Then() is invalid; separate distinct throwing steps with Then().