HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpMinor

Verifying the type of an AggregateException's inner exception in a unit test

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
aggregateexceptionverifyingtheexceptiontypetestinnerunit

Problem

I've got the following code inside an integration test.

[TestMethod]
public void Integration_GetUser_WithoutLoggingIn_ThrowsInvalidOperationException()
{
    var myApi = new Api(new Session());

    try
    {
        var irrelevant = myApi.GetUserInfoAsync().AsTask().Result;
    }
    catch (AggregateException ae)
    {
        if (ae.InnerException.GetType() == typeof(InvalidOperationException))
        {
            Assert.IsTrue(true);
        }
        else
        {
            Assert.Fail("There was no InvalidOperationException.");
        }
    }
}


Some remarks about it:

  • I am writing a Windows Runtime Component so the return type has to be IAsyncOperation, Task is not an option.



  • I am blocking the call using AsTask().Result, is this the most appropriate method?



  • Exceptions thrown in an asynchronous chain return AggregateException so I want to inspect that it throws the exception which I defined as "you are not logged in".



  • I'm using MSTest because NUnit can't handle WinRT types (which stinks in combination with integration tests).

Solution

I am blocking the call using AsTask().Result, is this the most appropriate method?

Can't you use await? Most testing frameworks (apparently including MSTest) support async tests. That way, you could work directly with the inner exception instead of the AggregateException.

if (ae.InnerException.GetType() == typeof(InvalidOperationException))
{
    Assert.IsTrue(true);
}
else
{
    Assert.Fail("There was no InvalidOperationException.");
}


I think this should be shortened to just:

Assert.AreEqual(typeof(InvalidOperationException), ae.InnerException.GetType());


Or maybe:

Assert.AreEqual(
    typeof(InvalidOperationException), ae.InnerException.GetType(),
    "There was no InvalidOperationException.");



Exceptions thrown in an asynchronous chain return AggregateException so I want to inspect that it throws the exception which I defined as "you are not logged in".

But you're not doing that, you're just checking that it's InvalidOperationException. If you want to test for this, maybe you should use a custom exception type?

Code Snippets

if (ae.InnerException.GetType() == typeof(InvalidOperationException))
{
    Assert.IsTrue(true);
}
else
{
    Assert.Fail("There was no InvalidOperationException.");
}
Assert.AreEqual(typeof(InvalidOperationException), ae.InnerException.GetType());
Assert.AreEqual(
    typeof(InvalidOperationException), ae.InnerException.GetType(),
    "There was no InvalidOperationException.");

Context

StackExchange Code Review Q#55135, answer score: 7

Revisions (0)

No revisions yet.