anatol
anatol

Reputation: 1760

XUnit Assert.IsType() with multiple expected types

I need to check one from three possible types of exceptions. If one of these exceptions thrown, the test considered passed. I'm using [Theory] and [MemberData] for several scenarios.

[Theory]
[MemberData(nameof(GetInvalidMimeMessages))]
public async Task ProcessAsync_TestFail(MimeMessage message)
{
    var stub = Mock.Of<IOptions<ScrapyardFilesOptions>>(s => s.Value.ConnectionString == "UseDevelopmentStorage=true" && s.Value.Container == "exchange");
    var loggerMock = new Mock<ILogger<ScrapyardFilesHandler>>(MockBehavior.Loose);
    var scrapyard = new ScrapyardFilesHandler(loggerMock.Object, stub);
    var ex = await Assert.ThrowsAnyAsync<Exception>(() => scrapyard.ProcessAsync(message));

    // imagine solution somehow like that
    Assert.IsType( 
                    { 
                      typeof(NullReferenceException)    ||
                      typeof(KeyNotFoundException)      ||
                      typeof(InvalidOperationException) ||
                    },
                    ex); 
}

private static IEnumerable<object[]> GetInvalidMimeMessages()
{
    yield return new object[] { null };
    yield return new object[] { new MimeMessage() };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("[email protected]"), new MailboxAddress("[email protected]"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("[email protected]"), new MailboxAddress("[email protected]"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
}

How can I get such assert?

Upvotes: 0

Views: 5427

Answers (2)

anatol
anatol

Reputation: 1760

var exceptions = new List<Type>()
            {
                typeof(NullReferenceException),
                typeof(KeyNotFoundException),
                typeof(InvalidOperationException),
            };

var ex = await Assert.ThrowsAnyAsync<Exception>(() => foo.Bar());
Assert.Contains(ex.GetType(), exceptions);

Upvotes: 5

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37070

As you have multiple possible exceptions to be thrown there´s no built-in way in NUnit to check this. If you´re only up for one exception you could use this:

Assert.Throws<NullReferenceException>(() => DoSomething);

However with multiple ones you can use good old try-catch:

try
{
    DoSomething();
}
catch(NullReferenceException) { Assert.Pass(); }
catch(KeyNotFoundException) { Assert.Pass(); }
catch(InvalidOperationException) { Assert.Pass(); }
catch(Exception) { Assert.Fail("Unexpected exception was caught"); }
Assert.Fail("No exception was caught");

Upvotes: 2

Related Questions