Geeks With Blogs

News
Joe Mayo

In previous versions of LINQ to Twitter, I used XUnit, which has a nice Assert.Throws method that I used a lot. When I started the PCL version of LINQ to Twitter, I started using MSTest and missed Assert.Throws right away.

 

Searching around, I found Bradley Braithwaite’s excellent blog post, Asserting Exceptions in MSTest with Assert.Throws(). Since the new version of LINQ to Twitter is async, I altered his code to create an async version of Assert.Throws, shown here:

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LinqToTwitterPcl.Tests.Common
{
    class L2TAssert
    {
        public static async Task Throws(Func task) 
            where T : Exception
        {
            try
            {
                await task();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(T));
                return (T)ex;
            }

            if (typeof(T).Equals(new Exception().GetType()))
                Assert.Fail("Expected exception but no exception was thrown.");
            else
                Assert.Fail(
                    string.Format(
                        "Expected exception of type {0} but no exception was thrown.", 
                        typeof(T)));

            return null;
        }
    }
}

In this situation, it would have been nice to be able to add extension methods to static classes and all of my code would have worked without problems, but no such luck. The simple work-around I chose was to rename the class to L2TAssert. Notice that Throws is async, returns Task, and awaits the Func task . My testing logic isn’t too sophisticated, so I only use one overload.

This way, I can keep nearly the same logic as I had before, except for the class name change, shown below:

        [TestMethod]
        public async Task CreateListAsync_Requires_ListName()
        {
            InitializeTwitterContext();

            var ex = await L2TAssert.Throws(
                async () => await ctx.CreateListAsync(null, "public", "desc"));

            Assert.AreEqual("listName", ex.ParamName);
        }

The test method is async, returns a Task, the code awaits L2TAssert.Throws, the lambda is async and awaits the method call – to create a new Twitter List in this case. Now, I don’t have to rewrite code to use an attribute or try/catch.

@JoeMayo

Posted on Tuesday, November 26, 2013 9:58 PM unit testing | Back to top

Copyright © Joe Mayo | Powered by: GeeksWithBlogs.net